Sie sind auf Seite 1von 30

This is a linux command line reference for common operations.

Examples marked with are valid/safe to paste without modification into a terminal, so you may want to keep a terminal window open while reading this so you can cut & paste. All these commands have been tested both on Fedora and Ubuntu. See also more linux commands. Command apropos whatis man -t ascii | ps2pdf - > ascii.pdf which command time command time cat dir navigation cd cd (cd dir && command) pushd . file searching alias l='ls -l --color=auto' ls -lrt ls /usr/bin | pr -T9 -W$COLUMNS find -name '*.[ch]' | xargs grep -E 'expr' find -type f -print0 | xargs -r0 grep -F 'example' find -maxdepth 1 -type f | xargs grep -F 'example' find -maxdepth 1 -type d | while read dir; do echo $dir; echo cmd2; done find -type f ! -perm -444 Description Show commands pertinent to string. See also threadsafe make a pdf of a manual page Show full path name of command See how long a command takes Start stopwatch. Ctrl-d to stop. See also sw Go to previous directory Go to $HOME directory Go to dir, execute command and return to current dir Put current dir on stack so you can popd back to it quick dir listing List files by date. See also newest and find_mm_ yyyy Print in 9 columns to width of terminal Search 'expr' in this dir and below. See also findrepo Search all regular files for 'example' in this dir and below Search all regular files for 'example' in this dir Process each item with multiple commands (in while loop) Find files not readable by all (useful for web site)

find -type d ! -perm -111 locate -r 'file[^/]*\.txt' look reference grep --color reference /usr/share/dict/words archives and compression gpg -c file gpg file.gpg

Find dirs not accessible by all (useful for web site) Search cached index for names. This re is like glob *file*.txt Quickly search (sorted) dictionary for prefix Highlight occurances of regular expression in dictionary

Encrypt file Decrypt file Make compressed archive tar -c dir/ | bzip2 > dir.tar.bz2 of dir/ Extract archive (use gzip bzip2 -dc dir.tar.bz2 | tar -x instead of bzip2 for tar.gz files) Make encrypted archive of tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg' dir/ on remote machine find dir/ -name '*.txt' | tar -c --files-from=- | bzip2 > Make archive of subset of dir_txt.tar.bz2 dir/ and below find dir/ -name '*.txt' | xargs cp -a --target-directory=dir_txt/ -- Make copy of subset of dir/ parents and below Copy (with permissions) ( tar -c /dir/to/copy ) | ( cd /where/to/ && tar -x -p ) copy/ dir to /where/to/ dir Copy (with permissions) ( cd /dir/to/copy && tar -c . ) | ( cd /where/to/ && tar -x -p ) contents of copy/ dir to /where/to/ Copy (with permissions) ( tar -c /dir/to/copy ) | ssh -C user@remote 'cd /where/to/ && copy/ dir to tar -x -p' remote:/where/to/ dir Backup harddisk to remote dd bs=1M if=/dev/sda | gzip | ssh user@remote 'dd of=sda.gz' machine rsync (Network efficient file copier: Use the --dry-run option for testing) Only get diffs. Do multiple rsync -P rsync://rsync.server.com/path/to/file file times for troublesome downloads Locally copy with rate rsync --bwlimit=1000 fromfile tofile limit. It's like nice for I/O Mirror web site (using rsync -az -e ssh --delete ~/public_html/ compression and remote.com:'~/public_html' encryption) rsync -auz -e ssh remote:/dir/ . && rsync -auz -e Synchronize current ssh . remote:/dir/ directory with remote one

ssh (Secure SHell) ssh $USER@$HOST command ssh -f -Y $USER@$HOSTNAME xeyes scp -p -r $USER@$HOST: file dir/ Run command on $HOST as $USER (default command=shell) Run GUI command on $HOSTNAME as $USER Copy with permissions to $USER's home directory on $HOST Use faster crypto for local LAN. This might saturate GigE Forward connections to $HOSTNAME:8080 out to $HOST:80 Forward connections from $HOST:1434 in to imap:143 Install public key for $USER@$HOST for password-less log in Store local browsable version of a page to the current dir Continue downloading a partially downloaded file Download a set of files to the current directory FTP supports globbing directly Process output directly

scp -c arcfour $USER@$LANHOST: bigfile

ssh -g -L 8080:localhost:80 root@$HOST

ssh -R 1434:imap:143 root@$HOST

ssh-copy-id $USER@$HOST wget (multi purpose download tool) (cd dir/ && wget -nd -pHEKk http://www.pixelbeat.org/cmdline.html) wget -c http://www.example.com/large.file wget -r -nd -np -l1 -A '*.jpg' http://www.example.com/dir/ wget ftp://remote/file[1-9].iso/ wget -q -O- http://www.pixelbeat.org/timeline.html | grep 'a href' | head echo 'wget url' | at 01:00

Download url at 1AM to current dir Do a low priority download wget --limit-rate=20k url (limit to 20KB/s in this case) wget -nv --spider --force-html -i bookmarks.html Check links in a file Efficiently update a local wget --mirror http://www.example.com/ copy of a site (handy from cron) networking (Note ifconfig, route, mii-tool, nslookup commands are obsolete) Show status of ethernet ethtool eth0 interface eth0

Manually set ethernet interface speed Show status of wireless iwconfig eth1 interface eth1 Manually set wireless iwconfig eth1 rate 1Mb/s fixed interface speed List wireless networks in iwlist scan range ip link show List network interfaces Rename interface eth0 to ip link set dev eth0 name wan wan Bring interface eth0 up (or ip link set dev eth0 up down) List addresses for ip addr show interfaces Add (or del) ip and mask ip addr add 1.2.3.4/24 brd + dev eth0 (255.255.255.0) ip route show List routing table Set default gateway to ip route add default via 1.2.3.254 1.2.3.254 Lookup DNS ip address for host pixelbeat.org name or vice versa Lookup local ip address hostname -i (equivalent to host `hostname`) Lookup whois info for whois pixelbeat.org hostname or ip address List internet services on a netstat -tupl system List active connections netstat -tup to/from system windows networking (Note samba is the package that provides all this windows specific networking support) Find windows machines. smbtree See also findsmb Find the windows (netbios) nmblookup -A 1.2.3.4 name associated with ip address List shares on windows smbclient -L windows_box machine or samba server mount -t smbfs -o fmask=666,guest //windows_box/share Mount a windows share /mnt/share Send popup to windows echo 'message' | smbclient -M windows_box machine (off by default in XP sp2) ethtool --change eth0 autoneg off speed 100 duplex full

text manipulation (Note sed uses stdin and stdout. Newer versions support inplace editing with the -i option) Replace string1 with sed 's/string1/string2/g' string2 Modify anystring1 to sed 's/\(.*\)1/\12/g' anystring2 Remove comments and sed '/ *#/d; /^ *$/d' blank lines Concatenate lines with sed ':a; /\\$/N; s/\\\n//; ta' trailing \ Remove trailing spaces sed 's/[ \t]*$//' from lines Escape shell sed 's/\([`"$\]\)/\\\1/g' metacharacters active within double quotes seq 10 | sed "s/^/ /; s/ *\(.\{7,\}\)/\1/" Right align numbers sed -n '1000{p;q}' Print 1000th line sed -n '10,20p;20q' Print lines 10 to 20 Extract title from HTML sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q' web page sed -i 42d ~/.ssh/known_hosts Delete a particular line sort -t. -k1,1n -k2,2n -k3,3n -k4,4n Sort IPV4 ip addresses echo 'Test' | tr '[:lower:]' '[:upper:]' Case conversion Filter non printable tr -dc '[:print:]' < /dev/urandom characters cut fields separated by tr -s '[:blank:]' '\t' </proc/diskstats | cut -f4 blanks history | wc -l Count lines set operations (Note you can export LANG=C for speed. Also these assume no duplicate lines within a file) sort file1 file2 | uniq Union of unsorted files Intersection of unsorted sort file1 file2 | uniq -d files sort file1 file1 file2 | uniq -u Difference of unsorted files Symmetric Difference of sort file1 file2 | uniq -u unsorted files join -t'\0' -a1 -a2 file1 file2 Union of sorted files join -t'\0' file1 file2 Intersection of sorted files join -t'\0' -v2 file1 file2 Difference of sorted files Symmetric Difference of join -t'\0' -v1 -v2 file1 file2 sorted files math Quick math (Calculate ). echo '(1 + sqrt(5))/2' | bc -l See also bc

seq -f '4/%g' 1 2 99999 | paste -sd-+ | bc -l echo 'pad=20; min=64; (100*10^6)/((pad+min)*8)' | bc echo 'pad=20; min=64; print (100E6)/((pad+min)*8)' | python echo 'pad=20; plot [64:1518] (100*10**6)/((pad+x)*8)' | gnuplot -persist

echo 'obase=16; ibase=10; 64206' | bc echo $((0x2dec)) units -t '100m/9.58s' 'miles/hour' units -t '500GB' 'GiB' units -t '1 googol' seq 100 | (tr '\n' +; echo 0) | bc calendar cal -3 cal 9 1752 date -d fri [ $(date -d "tomorrow" +%d) = "01" ] || exit date --date='25 Dec' +%A date --date='@2147483647'

Calculate the unix way More complex (int) e.g. This shows max FastE packet rate Python handles scientific notation Plot FastE packet rate vs packet size Base conversion (decimal to hexadecimal) Base conversion (hex to dec) ((shell arithmetic expansion)) Unit conversion (metric to imperial) Unit conversion (SI to IEC prefixes) Definition lookup Add a column of numbers. See also add and funcpy Display a calendar Display a calendar for a particular month year What date is it this friday. See also day exit a script unless it's the last day of the month What day does xmas fall on, this year Convert seconds since the epoch (1970-01-01 UTC) to date What time is it on west coast of US (use tzselect to find TZ) What's the local time for 9AM next Friday on west coast US Print number with thousands grouping appropriate to locale Use locale thousands grouping in ls. See also l

TZ='America/Los_Angeles' date

date --date='TZ="America/Los_Angeles" 09:00 next Fri' locales printf "%'d\n" 1234 BLOCK_SIZE=\'1 ls -l

echo "I live in `locale territory`" LANG=en_IE.utf8 locale int_prefix locale -kc $(locale | sed -n 's/\(LC_.\{4,\}\)=.*/\1/p') | less recode (Obsoletes iconv, dos2unix, unix2dos) recode -l | less recode windows-1252.. file_to_change.txt recode utf-8/CRLF.. file_to_change.txt recode iso-8859-15..utf8 file_to_change.txt recode ../b64 < file.txt > file.b64 recode /qp.. < file.qp > file.txt recode ..HTML < file.txt > file.html recode -lf windows-1252 | grep euro echo -n 0x80 | recode latin-9/x1..dump echo -n 0x20AC | recode ucs-2/x2..latin-9/x echo -n 0x20AC | recode ucs-2/x2..utf-8/x CDs gzip < /dev/cdrom > cdrom.iso.gz mkisofs -V LABEL -r dir | gzip > cdrom.iso.gz mount -o loop cdrom.iso /mnt/dir cdrecord -v dev=/dev/cdrom blank=fast gzip -dc cdrom.iso.gz | cdrecord -v dev=/dev/cdrom cdparanoia -B cdrecord -v dev=/dev/cdrom -audio -pad *.wav oggenc --tracknum='track' track.cdda.wav -o 'track.ogg' disk space (See also FSlint)

Extract info from locale database Lookup locale info for specific country. See also ccodes List fields available in locale database Show available conversions (aliases on each line) Windows "ansi" to local charset (auto does CRLF conversion) Windows utf8 to local charset Latin9 (western europe) to utf8 Base64 encode Quoted printable decode Text to HTML Lookup table of characters Show what a code represents in latin-9 charmap Show latin-9 encoding Show utf-8 encoding Save copy of data cdrom Create cdrom image from contents of dir Mount the cdrom image at /mnt/dir (read only) Clear a CDRW Burn cdrom image (use dev=ATAPI -scanbus to confirm dev) Rip audio tracks from CD to wav files in current dir Make audio CD from all wavs in current dir (see also cdrdao) Make ogg file from wav file

Show files by size, biggest last Show top disk users in du -s * | sort -k1,1rn | head current dir. See also dutop Sort paths by easy to du -hs /home/* | sort -k1,1h interpret disk usage Show free space on df -h mounted filesystems Show free inodes on df -i mounted filesystems Show disks partitions sizes fdisk -l and types (run as root) List all packages by rpm -q -a --qf '%10{SIZE}\t%{NAME}\n' | sort -k1,1n installed size (Bytes) on rpm distros List all packages by dpkg-query -W -f='${Installed-Size;10}\t${Package}\n' | sort installed size (KBytes) on k1,1n deb distros Create a large test file dd bs=1 seek=2TB if=/dev/null of=ext3.test (taking no space). See also truncate truncate data of file or > file create an empty file monitoring/debugging Monitor messages in a log tail -f /var/log/messages file Summarise/profile system strace -c ls >/dev/null calls made by command List system calls made by strace -f -e open ls >/dev/null command Monitor what's written to strace -f -e trace=write -e write=1,2 ls >/dev/null stdout and stderr List library calls made by ltrace -f -e getenv ls >/dev/null command List paths that process id lsof -p $$ has open List processes that have lsof ~ specified path open Show network traffic tcpdump not port 22 except ssh. See also tcpdump_not_me List processes in a ps -e -o pid,args --forest hierarchy ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed '/^ 0.0 List processes by % cpu /d' usage ls -lSr

List processes by mem (KB) usage. See also ps_mem.py List all threads for a ps -C firefox-bin -L -o pid,tid,pcpu,state particular process List elapsed wall time for ps -p 1,$$ -o etime= particular process IDs last reboot Show system reboot history Show amount of free -m (remaining) RAM (-m displays in MB) Watch changeable data watch -n.1 'cat /proc/interrupts' continuously Monitor udev events to udevadm monitor help configure rules system information (see also sysinfo) ('#' means root access is required) Show kernel version and uname -a system architecture Show name and version of head -n1 /etc/issue distribution Show all partitions cat /proc/partitions registered on the system Show RAM total seen by grep MemTotal /proc/meminfo the system grep "model name" /proc/cpuinfo Show CPU(s) info lspci -tv Show PCI info lsusb -tv Show USB info List mounted filesystems mount | column -t on the system (and align output) Show state of cells in grep -F capacity: /proc/acpi/battery/BAT0/info laptop battery Display SMBIOS/DMI # dmidecode -q | less information How long has this disk # smartctl -A /dev/sda | grep Power_On_Hours (system) been powered on in total # hdparm -i /dev/sda Show info about disk sda Do a read speed test on # hdparm -tT /dev/sda disk sda Test for unreadable blocks # badblocks -s /dev/sda on disk sda interactive (see also linux keyboard shortcuts) Line editor used by bash, readline python, bc, gnuplot, ... ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS

screen mc gnuplot links xdg-open . Command grep . /proc/sys/net/ipv4/* set | grep $USER tr '\0' '\n' < /proc/$$/environ echo $PATH | tr : '\n' kill -0 $$ && echo process exists and can accept signals find /etc -readable | xargs less -K -p'*ntp' -j $((${LINES:25}/2))

Virtual terminals with detach capability, ... Powerful file manager that can browse rpm, tar, ftp, ssh, ... Interactive/scriptable graphing Web browser open a file or url with the registered desktop application Description List the contents of flag files Search current environment Display the startup environment for any process Display the $PATH one per line Check for the existence of a process (pid) Search paths and data with full context. Use n to iterate Rate limit apt-get to 42KB/s Download url at 1AM to current dir Restart apache if config is OK Run a low priority command (openssl benchmark) Make shell (script) low priority. Use for non interactive tasks

Low impact admin apt-get install "package" -o Acquire::http::Dl-Limit=42 \ # -o Acquire::Queue-mode=access echo 'wget url' | at 01:00 # apache2ctl configtest && apache2ctl graceful nice openssl speed sha1

renice 19 -p $$; ionice -c3 -p $$ Interactive monitoring watch -t -n1 uptime

Clock with system load Better top (scrollable, tree htop -d 5 view, lsof/strace integration, ...) iotop What's doing I/O # watch -d -n30 "nice ps_mem.py | tail -n $((${LINES:-12}-2))" What's using RAM

# iftop # mtr www.pixelbeat.org Useful utilities pv < /dev/zero > /dev/null

What's using the network. See also iptraf ping and traceroute combined Progress Viewer for data copying from files and pipes

wkhtml2pdf http://.../linux_commands.html linux_commands.p Make a pdf of a web page df run a command with timeout 1 sleep 3 bounded time. See also timeout Networking Serve current directory tree python -m SimpleHTTPServer at http://$HOSTNAME:80 00/ openssl s_client -connect www.google.com:443 </dev/null Display the date range for a 2>&0 | site's certs openssl x509 -dates -noout Display the server headers curl -I www.pixelbeat.org for a web site # lsof -i tcp:80 What's using port 80 Display a list of apache # httpd -S virtual hosts Edit remote file using local vim scp://user@remote//path/to/file vim. Good for high latency links Import a gpg key from the curl -s http://www.pixelbeat.org/pixelbeat.asc | gpg --import web Add 20ms latency to tc qdisc add dev lo root handle 1:0 netem delay 20msec loopback device (for testing) Remove latency added tc qdisc del dev lo root above Notification echo "DISPLAY=$DISPLAY xmessage cooker" | at "NOW Popup reminder +30min" Display a gnome popup notify-send "subject" "message" notification echo "mail -s 'go home' P@draigBrady.com < /dev/null" | at Email reminder 17:30 uuencode file name | mail -s subject P@draigBrady.com Send a file via email ansi2html.sh | mail -a "Content-Type: text/html" Send/Generate HTML P@draigBrady.com email

Better default settings (useful in your .bashrc) # tail -s.1 -f /var/log/messages seq 100 | tail -n $((${LINES:-12}-2)) # tcpdump -s0 Useful functions/aliases (useful in your .bashrc) md () { mkdir -p "$1" && cd "$1"; } strerror() { python -c "import os; print os.strerror($1)"; } plot() { { echo 'plot "-"' "$@"; cat; } | gnuplot -persist; } hili() { e="$1"; shift; grep --col=always -Eih "$e|$" "$@"; } alias hd='od -Ax -tx1z -v' alias realpath='readlink -f' Multimedia DISPLAY=:0.0 import -window root orig.png Display file additions more responsively Display as many lines as possible without scrolling Capture full network packets Change to a new directory Display the meaning of an errno Plot stdin. (e.g: seq 1000 | sed 's/.*/s(&)/' | bc -l | plot) highlight occurences of expr. (e.g: env | hili $USER) Hexdump. (usage e.g.: hd /proc/self/cmdline | less) Canonicalize path. (usage e.g.: realpath ~/../$USER)

Take a (remote) screenshot Shrink to width, computer convert -filter catrom -resize '600x>' orig.png 600px_wide.png gen images or screenshots Extract audio from flash mplayer -ao pcm -vo null -vc dummy /tmp/Flash* video to audiodump.wav Display info about ffmpeg -i filename.avi multimedia file Capture video of an X ffmpeg -f x11grab -s xga -r 25 -i :0 -sameq demo.mpg display DVD Convert video to the for i in $(seq 9); do ffmpeg -i $i.avi -target pal-dvd $i.mpg; correct encoding and aspect done for DVD Build DVD file system. dvdauthor -odvd -t -v "pal,4:3,720xfull" *.mpg;dvdauthor Use 16:9 for widescreen odvd -T input Burn DVD file system to growisofs -dvd-compat -Z /dev/dvd -dvd-video dvd disc Unicode python -c "import unicodedata as u; print Lookup a unicode character u.name(unichr(0x2028))" Normalize combining uconv -f utf8 -t utf8 -x nfc characters printf '\300\200' | iconv -futf8 -tutf8 >/dev/null Validate UTF-8

printf ' TF8\n' | LANG=C grep --color=always '[^ -~]\+' fc-match -s "sans:lang=zh" Development

Highlight non printable ASCII chars in UTF-8 List font match order for language and style

Show autodetected gcc tuning params. See also gcccpuopt for i in $(seq 4); do { [ $i = 1 ] && wget http://url.ie/6lko -qO-|| Compile and execute C ./a.out; } | tee /dev/tty | gcc -xc - 2>/dev/null; done code from stdin Show all predefined cpp -dM /dev/null macros echo "#include <features.h>" | cpp -dN | grep "#define Show all glibc feature __USE_" macros Debug showing source gdb -tui code context in separate windows Extended Attributes (Note you may need to (re)mount with "acl" or "user_xattr" options) getfacl . Show ACLs for file Allow a specific user to setfacl -m u:nobody:r . read file Delete a specific user's setfacl -x u:nobody . rights to file Set umask for a for a setfacl --default -m group:users:rw- dir/ specific dir Show capabilities for a getcap file program Allow gtk program raw setcap cap_net_raw+ep your_gtk_prog access to network Show SELinux context for stat -c%C . file Set SELinux context for chcon ... file file (see also restorecon) Show all extended getfattr -m- -d . attributes (includes selinux,acls,...) setfattr -n "user.foo" -v "bar" . Set arbitrary user attributes BASH specific Split data to 2 commands echo 123 | tee >(tr 1 a) | tr 1 b (using process substitution) Compare a local and meld local_file <(ssh host cat remote_file) remote file (using process substitution) Multicore taskset -c 0 nproc Restrict a command to gcc -march=native -E -v -</dev/null 2>&1|sed -n 's/.*-mar/mar/p'

find -type f -print0 | xargs -r0 -P$(nproc) -n10 md5sum sort -m <(sort data1) <(sort data2) >data.sorted

certain processors Process files in parallel over available processors Sort separate data files over 2 processors

An A-Z Index of the Bash command line for Linux.


adduser Add a user to the system addgroup Add a group to the system alias Create an alias apropos Search Help manual pages (man -k) apt-get Search for and install software packages (Debian/Ubuntu) aptitude Search for and install software packages (Debian/Ubuntu) aspell Spell Checker awk Find and Replace text, database sort/validate/index b basename Strip directory and suffix from filenames bash GNU Bourne-Again SHell bc Arbitrary precision calculator language bg Send to background break Exit from a loop builtin Run a shell builtin bzip2 Compress or decompress named file(s) c cal Display a calendar case Conditionally perform a command cat Display the contents of a file cd Change Directory cfdisk Partition table manipulator for Linux chgrp Change group ownership chmod Change access permissions chown Change file owner and group chroot Run a command with a different root directory chkconfig System services (runlevel) cksum Print CRC checksum and byte counts clear Clear terminal screen cmp Compare two files comm Compare two sorted files line by line command Run a command - ignoring shell functions continue Resume the next iteration of a loop

cp cron crontab csplit cut d

Copy one or more files to another location Daemon to execute scheduled commands Schedule a command to run at a later time Split a file into context -determined pieces Divide a file into several par ts

date Display or change the date & time dc Desk Calculator dd Convert and copy a file, write disk h eaders, boot records ddrescue Data recovery tool declare Declare variables and give them attributes df Display free disk space diff Display the differences between two files diff3 Show differences among three files dig DNS lookup dir Briefly list directory contents dircolors Colour setup for `ls' dirname Convert a full pathname to just a path dirs Display list of remembered directories dmesg Print kernel & driver messages du Estimate file space usage e echo Display message on screen egrep Search file(s) for lines that match an extended expression eject Eject removable media enable Enable and disable builtin shell commands env Environment variables ethtool Ethernet card settings eval Evaluate several commands/arguments exec Execute a command exit Exit the shell expect Automate arbitrary applications accessed over a terminal expand Convert tabs to spaces export Set an environment variable expr Evaluate expressions f false Do nothing, unsuccessfully fdformat Low-level format a floppy disk fdisk Partition table manipulator for Linux fg Send job to foreground fgrep Search file(s) for lines that match a fixed string file Determine file type find Search for files that meet a desired criteria fmt Reformat paragraph text fold Wrap text to fit a specified width. for Expand words, and execute commands format Format disks or tapes free Display memory usage

fsck ftp function fuser g gawk getopts grep groups gzip h hash head help history hostname i iconv id if ifconfig ifdown ifup import file install j jobs join k kill killall l less let ln local locate logname logout look lpc lpr lprint lprintd lprintq lprm ls lsof m make

File system consistency check and repair File Transfer Protocol Define Function Macros Identify/kill the process that is accessing a file Find and Replace text within file(s) Parse positional parameters Search file(s) for lines that match a given pattern Print group names a user is in Compress or decompress named file(s) Remember the full pathname of a name argument Output the first part of file(s) Display help for a built -in command Command History Print or set system name Convert the character set of a file Print user and group id's Conditionally perform a command Configure a network interface Stop a network interface Start a network interface up Capture an X server screen and save the image to Copy files and set attributes List active jobs Join lines on a common field Stop a process from running Kill processes by name Display output one screen at a time Perform arithmetic on shell variables Make links between files Create variables Find files Print current login name Exit a login shell Display lines beginning with a given string Line printer control program Off line print Print a file Abort a print job List the print queue Remove jobs from the print queue List information about file(s) List open files Recompile a group of programs

man mkdir mkfifo mkisofs mknod more mount mtools mtr mv mmv n

Help manual Create new folder(s) Make FIFOs (named pipes) Create an hybrid ISO9660/JOLIET/HFS filesystem Make block or character special files Display output one screen at a time Mount a file system Manipulate MS-DOS files Network diagnostics (traceroute/ping) Move or rename files or directories Mass Move and rename (files)

netstat Networking information nice Set the priority of a command or job nl Number lines and write files nohup Run a command immune to hangups notify-send Send desktop notifications nslookup Query Internet name servers interactively o open op p passwd paste pathchk ping pkill popd pr printcap printenv printf ps pushd pwd q quota Display disk usage and limits quotacheck Scan a file system for disk usage quotactl Set disk quotas r ram ram disk device rcp Copy files between two machines read Read a line from standard input readarray Read from stdin into an array variable readonly Mark variables/functions as readonly reboot Reboot the system rename Rename files renice Alter priority of running processes remsync Synchronize remote files via email return Exit a shell function rev Reverse lines of a file Modify a user password Merge lines of files Check file name portability Test a network connection Stop processes from running Restore the previous value of the current directory Prepare files for printing Printer capability database Print environment variables Format and print data Process status Save and then change the current directory Print Working Directory Open a file in its default application Operator access

rm rmdir rsync s screen scp sdiff sed select seq set sftp shift shopt shutdown sleep slocate sort source split ssh strace su sudo sum suspend symlink sync t

Remove files Remove folder(s) Remote file copy (Synchronize file trees) Multiplex terminal, run remote shells via ssh Secure copy (remote file copy) Merge two files interactively Stream Editor Accept keyboard input Print numeric sequences Manipulate shell variables and functions Secure File Transfer Program Shift positional parameters Shell Options Shutdown or restart linux Delay for a specified time Find files Sort text files Run commands from a file `.' Split a file into fixed-size pieces Secure Shell client (remote login program) Trace system calls and signals Substitute user identity Execute a command as another user Print a checksum for a file Suspend execution of this shell Make a new name for a file Synchronize data on disk with memory

tail Output the last part of files tar Tape ARchiver tee Redirect output to multiple files test Evaluate a conditional expression time Measure Program running time times User and system times touch Change file timestamps top List processes running on the system traceroute Trace Route to Host trap Run a command when a signal is set(bourne) tr Translate, squeeze, and/or delete characters true Do nothing, successfully tsort Topological sort tty Print filename of terminal on stdin type Describe a command u ulimit umask umount unalias uname unexpand Limit user resources Users file creation mask Unmount a device Remove an alias Print system information Convert spaces to tabs

uniq units unset unshar until useradd usermod users uuencode uudecode v v vdir vi vmstat w

Uniquify files Convert units from one scale to another Remove variable or function names Unpack shell archive scripts Execute commands (until error) Create new user account Modify user account List users currently logged in Encode a binary file Decode a file created by uuenc ode Verbosely list directory contents (`ls -l -b') Verbosely list directory contents (`ls -l -b') Text Editor Report virtual memory statistics

watch Execute/display a program periodically wc Print byte, word, and line counts whereis Search the user's $path, man pages and source files for a program which Search the user's $path for a program file while Execute commands who Print all usernames currently logged in whoami Print the current user id and name (`id -un') Wget Retrieve web pages or files via HTTP, HTTPS or FTP write Send a message to another user x xargs Execute utility, passing constructed argument list(s) xdg-open Open a file or URL in the user's preferred application. yes Print a string until interrupted . Run a command script in the current shell ### Comment / Remark Commands marked are bash built-ins, these are available under all shells.

Linux Interview Questions and Answers


You need to see the last fifteen lines of the files dog, cat and horse. What command should you use?

tail -15 dog cat horse

The tail utility displays the end of a file. The -15 tells tail to display the last fifteen lines of each specified file.
Who owns the data dictionary?

The SYS user owns the data dictionary. The SYS and SYSTEM users are created when the database is created.
You routinely compress old log files. You now need to examine a log from two months ago. In order to view its contents without first having to deco mpress it, use the _________ utility.

zcat The zcat utility allows you to examine the contents of a compressed file much the same way that cat displays a file.
You suspect that you have two commands with the same name as the command is not producing the expected results. What command can you use to determine the location of the command being run?

which The which command searches your path until it finds a command that matches the command you are looking for and displays its full path.
You locate a command in the /bin directory but do not know what it does. What command can you use to determine its purpose.

whatis The whatis command displays a summary line from the man page for the specified command.
You wish to create a link to the /data directory i n bob's home directory so you issue the command ln /data /home/bob/datalink but the command fails. What option should you use in this command line to be successful.

Use the -F option In order to create a link to a directory you must use the -F option.
When you issue the command ls -l, the first character of the resulting display represents the file's ___________.

type The first character of the permission block designates the type of file that is being displayed.
What utility can you use to show a dynamic listing of running processes? __________

top The top utility shows a listing of all running processes that is dynamically updated.
Where is standard output usually directed?

to the screen or display By default, your shell directs standard output to your screen or display.

You wish to restore the file memo.ben which was backed up in the tarfile MyBackup.tar. What command should you type?

tar xf MyBackup.tar memo.ben This command uses the x switch to extract a file. Here the file memo.ben will be restored from the tarfile MyBackup.tar.
You need to view the contents of the tarfile called MyBackup.tar. What command would you use?

tar tf MyBackup.tar The t switch tells tar to display the contents and the f modifier specifies which file to examine.
You want to create a compressed backup of the users' home directories. What utility should you use?

tar You can use the z modifier with tar to compress your archive at the same time as creating it.
What daemon is responsible for tracking events on y our system?

syslogd The syslogd daemon is responsible for tracking system information and saving it to specified log files.
You have a file called phonenos that is almost 4,000 lines long. What text filter can you use to split it into four pieces each 1 ,000 lines long?

split The split text filter will divide files into equally sized pieces. The default length of each piece is 1,000 lines.
You would like to temporarily change your command line editor to be vi. What command should you type to change it?

set -o vi The set command is used to assign environment variables. In this case, you are instructing your shell to assign vi as your command line editor. However, once you log off and log back in you will return to the previously defined command line editor.
What account is created when you install Linux?

root Whenever you install Linux, only one user account is created. This is the superuser account also known as root.
What command should you use to check the number of files and disk space used and each user's defined quotas?

repquota The repquota command is used to get a report on the status of the quotas you have set including the amount of allocated space and amount of used space.

In order to run fsck on the root partition, the root partition must be mounted as

readonly You cannot run fsck on a partition that is mounted as read-write.


In order to improve your system's security you decide to implement shadow passwords. What command should you use?

pwconv The pwconv command creates the file /etc/shadow and changes all passwords to 'x' in the /etc/passwd file.
Bob Armstrong, who has a username of boba, calls to tell you he forgot his password. What command should you use to reset his command?

passwd boba The passwd command is used to change your password. If you do not specify a username, your password will be changed.
The top utility can be used to change the prio rity of a running process? Another utility that can also be used to change priority is ___________?

nice Both the top and nice utilities provide the capability to change the priority of a running process.
What command should you type to see all the file s with an extension of 'mem' listed in reverse alphabetical order in the /home/ben/memos directory.

ls -r /home/ben/memos/*.mem The -c option used with ls results in the files being listed in chronological order. You can use wildcards with the ls command to specify a pattern of filenames.
What file defines the levels of messages written to system log files?

kernel.h To determine the various levels of messages that are defined on your system, examine the kernel.h file.
What command is used to remove the password assigned to a group? gpasswd -r

The gpasswd command is used to change the password assigned to a group. Use the -r option to remove the password from the group.
What command would you type to use the cpio to create a backup called backup.cpio of all the users' home directories?

find /home | cpio -o > backup.cpio The find command is used to create a list of the files and directories contained in home. This list is then piped to the cpio utility as a list of files to include and the output is saved to a file called backup.cpio.

What can you type at a command line to determine which shell you are using?

echo $SHELL The name and path to the shell you are using is saved to the SHELL environment variable. You can then use the echo command to print out the value of any variable by preceding the variable's name with $. Therefore, typing echo $SHELL will display the name of your shell.
What type of local file server can you use to provide the distribution installation materials to the new machine during a network installation?

A) Inetd B) FSSTND C) DNS D) NNTP E) NFS E - You can use an NFS server to provide the distribution installation materials to the machine on which you are performing the installation. Answers a, b, c, and d are all valid items but none of them are file servers. Inetd is the superdaemon which controls all intermittently used network services. The FSSTND is the Linux File System Standard. DNS provides domain name resolution, and NNTP is the transfer protocol for usenet news.
If you type the command cat dog & > cat what would you see on your display? Choose one:

a. Any error messages only. b. The contents of the file dog. c. The contents of the file dog and any error messages. d. Nothing as all output is saved to the file cat. d When you use & > for redirection, it redirects both the standard output and standard error. The output would be saved to the file cat.
You are covering for another system administrator and one of the users asks you to restore a file for him. You locat e the correct tarfile by checking the backup log but do not know how the directory structure was stored. What command can you use to determine this?

Choose one: a. tar fx tarfile dirname b. tar tvf tarfile filename c. tar ctf tarfile d. tar tvf tarfile d The t switch will list the files contained in the tarfile. Using the v modifier will display the stored directory structure.
You have the /var directory on its own partition. You have run out of space. What should you do? Choose one:

a. Reconfigure you r system to not write to the log files. b. Use fips to enlarge the partition. c. Delete all the log files. d. Delete the partition and recreate it with a larger size.

d The only way to enlarge a partition is to delete it and recreate it. You will then have to restore the necessary files from backup.
You have a new application on a CD -ROM that you wish to install. What should your first step be?

Choose one: a. Read the installation instructions on the CD -ROM. b. Use the mount command to mount your CD -ROM as read-write. c. Use the umount command to access your CD -ROM. d. Use the mount command to mount your CD -ROM as read-only. d Before you can read any of the files contained on the CD-ROM, you must first mount the CD-ROM.
When you create a new partition, you need to designate its size by defining the starting and ending _____________.

cylinders When creating a new partition you must first specify its starting cylinder. You can then either specify its size or the ending cylinder.
What key combination can you press to suspend a running job and place it in the background?

ctrl-z Using ctrl-z will suspend a job and put it in the background.
The easiest, most basic form of backing up a file is to _____ it to another location.

copy The easiest most basic form of backing up a file is to make a copy of that file to another location such as a floppy disk.
What type of server is used to remotely assign IP addresses to machines during the installation process?

A) SMB B) NFS C) DHCP D) FT E) HTTP C - You can use a DHCP server to assign IP addresses to individual machines during the installation process. Answers a, b, d, and e list legitimate Linux servers, but these servers do not provide IP addresses. The SMB, or Samba, tool is used for file and print sharing across multi-OS networks. An NFS server is for file sharing across Linux networks. FTP is a file storage server that allows people to browse and retrieve information by logging in to it, and HTTP is for the Web.
Which password package should you inst all to ensure that the central password file couldn't be stolen easily?

A) PAM B) tcp_wrappers C) shadow D) securepass E) ssh C - The shadow password package moves the central password file to a more secure location. Answers a, b, and e all point to valid packages, but none of these places the password file in a more secure location. Answer d points to an invalid package.
When using useradd to create a new user account, which of the following tasks is not done automatically.

Choose one: a. Assign a UID. b. Assign a default shell. c. Create the user's home directory. d. Define the user's home directory. c The useradd command will use the system default for the user's home directory. The home directory is not created, however, unless you use the -m option.
You want to enter a series of commands from the command -line. What would be the quickest way to do this?

Choose One a. Press enter after entering each command and its arguments b. Put them in a script and execute the script c. Separate each command with a semi-colon (;) and press enter after the last command d. Separate each command with a / and press enter after the last command c The semi-colon may be used to tell the shell that you are entering multiple commands that should be executed serially. If these were commands that you would frequently want to run, then a script might be more efficient. However, to run these commands only once, enter the commands directly at the command line.
You attempt to use shadow passwords but are unsuccessful. What characteristic of the /etc/passwd file may cause this?

Choose one: a. The login command is missing. b. The username is too long. c. The password field is blank. d. The password field is prefaced by an asterisk. c The password field must not be blank before converting to shadow passwords.
When you install a new application, documentation on that application is also usually installed. Where would you look for the documentation after installing an application called MyApp?

Choose one: a. /usr/MyApp

b. /lib/doc/MyApp c. /usr/doc/MyApp d. In the same directory where the application is installed. c The default location for application documentation is in a directory named for the application in the /usr/doc directory.
What file would you edit in your home dir ectory to change which window manager you want to use?

A) Xinit B) .xinitrc C) XF86Setup D) xstart E) xf86init Answer: B - The ~/.xinitrc file allows you to set which window man-ager you want to use when logging in to X from that account. Answers a, d, and e are all invalid files. Answer c is the main X server configuration file.
What command allows you to set a processor -intensive job to use less CPU time?

A) ps B) nice C) chps D) less E) more Answer: B - The nice command is used to change a job's priority level, so that it runs slower or faster. Answers a, d, and e are valid commands but are not used to change process information. Answer c is an invalid command.
While logged on as a regular user, your boss calls up and wants you to create a new user account immediately. How can you do this without first having to close your work, log off and logon as root?

Choose one: a. Issue the command rootlog. b. Issue the command su and type exit when finished. c. Issue the command su and type logoff when finishe d. d. Issue the command logon root and type exit when finished. Answer: b You can use the su command to imitate any user including root. You will be prompted for the password for the root account. Once you have provided it you are logged in as root and can do any administrative duties.
There are seven fields in the /etc/passwd file. Which of the following lists all the fields in the correct order?

Choose one: a. username, UID, GID, home directory, command, comment b. username, UID, GID, comment, home directory, command c. UID, username, GID, home directory, comment, command d. username, UID, group name, GID, home directory, comment Answer: b The seven fields required for each line in the /etc/passwd file are username, UID, GID,

comment, home directory, command. Each of these fields must be separated by a colon even if they are empty.
Which of the following commands will show a list of the files in your home directory including hidden files and the contents of all subdirectories?

Choose one: a. ls -c home b. ls -aR /home/username c. ls -aF /home/username d. ls -l /home/username Answer: b The ls command is used to display a listing of files. The -a option will cause hidden files to be displayed as well. The -R option causes ls to recurse down the directory tree. All of this starts at your home directory.
In order to prevent a user from logging in, you can add a(n) ________at the beginning of the password field.

Answer: asterick If you add an asterick at the beginning of the password field in the /etc/ passwd file, that user will not be able to log in.
You have a directory called /home/ben/memos and want to move it to /home/bob/memos so you issue the command mv /home/ben/memos /home/bob. What is the results of this action?

Choose one: a. The files contai ned in /home/ben/memos are moved to the directory /home/bob/memos/memos. b. The files contained in /home/ben/memos are moved to the directory /home/bob/memos. c. The files contained in /home/ben/memos are moved to the directory /home/bob/. d. The command f ails since a directory called memos already exists in the target directory. Answer: a When using the mv command to move a directory, if a directory of the same name exists then a subdirectory is created for the files to be moved.
Which of the following tasks is not necessary when creating a new user by editing the /etc/passwd file?

Choose one: a. Create a link from the user's home directory to the shell the user will use. b. Create the user's home directory c. Use the passwd command to assign a password to the account. d. Add the user to the specified group. Answer: a There is no need to link the user's home directory to the shell command. Rather, the specified shell must be present on your system.
You issue the following command useradd -m bobm But the user cannot logon. What is the problem?

Choose one: a. You need to assign a password to bobm's account using the passwd command.

b. You need to create bobm's home directory and set the appropriate permissions. c. You need to edit the /etc/passwd file and assign a shell for bobm's account. d. The username must be at least five characters long. Answer: a The useradd command does not assign a password to newly created accounts. You will still need to use the passwd command to assign a password.
You wish to print the file vacations with 60 lines to a page. Which of the following commands will accomplish this? Choose one:

a. pr -l60 vacations | lpr b. pr -f vacations | lpr c. pr -m vacations | lpr d. pr -l vacations | lpr Answer: a The default page length when using pr is 66 lines. The -l option is used to specify a different length.
Which file defines all users on your system?

Choose one: a. /etc/passwd b. /etc/users c. /etc/password d. /etc/user.conf Answer: a The /etc/passwd file contains all the information on users who may log into your system. If a user account is not contained in this file, then the user cannot log in.
Which two commands can you use to delete directories? A) rm B) rm -rf C) rmdir D) rd E) rd -rf

Answer(s): B, C - You can use rmdir or rm -rf to delete a directory. Answer a is incorrect, because the rm command without any specific flags will not delete a directory, it will only delete files. Answers d and e point to a non-existent command.
Which partitioning tool is available in all distributions?

A) Disk Druid B) fdisk C) Partition Magic D) FAT32 E) System Commander Answer(s): B - The fdisk partitioning tool is available in all Linux distributions. Answers a, c, and e all handle partitioning, but do not come with all distributions. Disk Druid is made by Red Hat and used in its distribution along with some derivatives. Partition Magic and System Commander are tools made by third-party companies. Answer d is not a tool, but a file system type. Specifically, FAT32 is the file system type used in Windows 98.

Which partitions might you create on the mail server's hard drive(s) other than the root, swap, and boot partitions?

[Choose all correct answers] A) /var/spool B) /tmp C) /proc D) /bin E) /home Answer(s): A, B, E - Separating /var/spool onto its own partition helps to ensure that if something goes wrong with the mail server or spool, the output cannot overrun the file system. Putting /tmp on its own partition prevents either software or user items in the /tmp directory from overrunning the file system. Placing /home off on its own is mostly useful for system re-installs or upgrades, allowing you to not have to wipe the /home hierarchy along with other areas. Answers c and d are not possible, as the /proc portion of the file system is virtual-held in RAM-not placed on the hard drives, and the /bin hierarchy is necessary for basic system functionality and, therefore, not one that you can place on a different partition.
When planning your backup strateg y you need to consider how often you will perform a backup, how much time the backup takes and what media you will use. What other factor must you consider when planning your backup strategy? _________

what to backup Choosing which files to backup is the first step in planning your backup strategy.
What utility can you use to automate rotation of logs?

Answer: logrotate The logrotate command can be used to automate the rotation of various logs.
In order to display the last five commands you have entere d using the history command, you would type ___________ .

Answer: history 5 The history command displays the commands you have previously entered. By passing it an argument of 5, only the last five commands will be displayed.
What command can you use to review boot messages?

Answer: dmesg The dmesg command displays the system messages contained in the kernel ring buffer. By using this command immediately after booting your computer, you will see the boot messages.
What is the minimum number of partition s you need to install Linux? Answer: 2 Linux can be installed on two partitions, one as / which will contain all files and a swap partition. What is the name and path of the main system log?

Answer: /var/log/messages By default, the main system log is /var/log/messages.


Of the following technologies, which is considered a client -side script?

A) JavaScript

B) Java C) ASP D) C++ Answer: A - JavaScript is the only client-side script listed. Java and C++ are complete programming languages. Active Server Pages are parsed on the server with the results being sent to the client in HTML

Das könnte Ihnen auch gefallen