7.
Linux 101 Hacks www.thegeekstuff.com ForewordAnother collection of hacks? Yes! If you have just completed your first admincourse or looking for better ways to get the job done the "Linux 101 Hacks"eBook is a good point to start. These useful tips are concise, well written andeasy to read.Well done - I will recommend this eBook to my students.--Prof. Dr. Fritz Mehner, FH Südwestfalen, Germany(Author of several Vim plugins, including bash-support vim plugin)VersionVersion Date Revisions1.0 12-Feb-2009 First EditionDownload the latest version of the book here. 8

8.
Linux 101 Hacks www.thegeekstuff.comChapter 1: Powerful CD Command Hackscd is one of the most frequently used commands during a UNIX session. The 6cd command hacks mentioned in this chapter will boost your productivityinstantly and make it easier to navigate the directory structure fromcommand line.Hack 1. Use CDPATH to define the base directory forcd commandIf you are frequently performing cd to subdirectories of a specific parentdirectory, you can set the CDPATH to the parent directory and perform cd tothe subdirectories without giving the parent directory path as explainedbelow. [ramesh@dev-db ~]# pwd /home/ramesh [ramesh@dev-db ~]# cd mail -bash: cd: mail: No such file or directory [Note: This is looking for mail directory under current directory] [ramesh@dev-db ~]# export CDPATH=/etc [ramesh@dev-db ~]# cd mail /etc/mail [Note: This is looking for mail under /etc and not under current directory] [ramesh@dev-db /etc/mail]# pwd /etc/mailTo make this change permanent, add export CDPATH=/etc to your~/.bash_profile 9

9.
Linux 101 Hacks www.thegeekstuff.comSimilar to the PATH variable, you can add more than one directory entry inthe CDPATH variable, separating them with : , as shown below. export CDPATH=.:~:/etc:/varThis hack can be very helpful under the following situations: o Oracle DBAs frequently working under $ORACLE_HOME, can set the CDPATH variable to the oracle home o Unix sysadmins frequently working under /etc, can set the CDPATH variable to /etc o Developers frequently working under project directory /home/projects, can set the CDPATH variable to /home/projects o End-users frequently accessing the subdirectories under their home directory, can set the CDPATH variable to ~ (home directory)Hack 2. Use cd alias to navigate up the directoryeffectivelyWhen you are navigating up a very long directory structure, you may be usingcd .... with multiple ..’s depending on how many directories you want to goup as shown below. # mkdir -p /tmp/very/long/directory/structure/that/is/too/deep # cd /tmp/very/long/directory/structure/that/is/too/deep # pwd /tmp/very/long/directory/structure/that/is/too/deep # cd ../../../../ 10

10.
Linux 101 Hacks www.thegeekstuff.com # pwd /tmp/very/long/directory/structureInstead of executing cd ../../../.. to navigate four levels up, use one of thefollowing three alias methods:Method 1: Navigate up the directory using “..n”In the example below, ..4 is used to go up 4 directory level, ..3 to go up 3directory level, ..2 to go up 2 directory level. Add the following alias to your~/.bash_profile and re-login. alias ..="cd .." alias ..2="cd ../.." alias ..3="cd ../../.." alias ..4="cd ../../../.." alias ..5="cd ../../../../.." # cd /tmp/very/long/directory/structure/that/is/too/deep # ..4 [Note: use ..4 to go up 4 directory level] # pwd /tmp/very/long/directory/structure/Method 2: Navigate up the directory using only dotsIn the example below, ….. (five dots) is used to go up 4 directory level.Typing 5 dots to go up 4 directory structure is really easy to remember, aswhen you type the first two dots, you are thinking “going up one directory”,after that every additional dot, is to go one level up. So, use …. (four dots) togo up 3 directory level and .. (two dots) to go up 1 directory level. Add thefollowing alias to your ~/.bash_profile and re-login for the ….. (five dots) towork properly. alias ..="cd .." 11

11.
Linux 101 Hacks www.thegeekstuff.com alias ...="cd ../.." alias ....="cd ../../.." alias .....="cd ../../../.." alias ......="cd ../../../../.." # cd /tmp/very/long/directory/structure/that/is/too/deep # ..... [Note: use ..... (five dots) to go up 4 directory level] # pwd /tmp/very/long/directory/structure/Method 3: Navigate up the directory using cd followed byconsecutive dots In the example below, cd….. (cd followed by five dots) is used to go up 4directory level. Making it 5 dots to go up 4 directory structure is really easy toremember, as when you type the first two dots, you are thinking “going upone directory”, after that every additional dot, is to go one level up. So, usecd…. (cd followed by four dots) to go up 3 directory level and cd… (cdfollowed by three dots) to go up 2 directory level. Add the following alias toyour ~/.bash_profile and re-login for the above cd….. (five dots) to workproperly. alias cd..="cd .." alias cd...="cd ../.." alias cd....="cd ../../.." alias cd.....="cd ../../../.." alias cd......="cd ../../../../.." # cd /tmp/very/long/directory/structure/that/is/too/deep # cd..... [Note: use cd..... to go up 4 directory level] # pwd /tmp/very/long/directory/structure 12

12.
Linux 101 Hacks www.thegeekstuff.comMethod 5: Navigate up the directory using cd followed by numberIn the example below, cd4 (cd followed by number 4) is used to go up 4directory level. alias cd1="cd .." alias cd2="cd ../.." alias cd3="cd ../../.." alias cd4="cd ../../../.." alias cd5="cd ../../../../.."Hack 3. Perform mkdir and cd using a singlecommandSometimes when you create a new directory, you may cd to the new directoryimmediately to perform some work as shown below. # mkdir -p /tmp/subdir1/subdir2/subdir3 # cd /tmp/subdir1/subdir2/subdir3 # pwd /tmp/subdir1/subdir2/subdir3Wouldn’t it be nice to combine both mkdir and cd in a single command? Addthe following to the .bash_profile and re-login. $ vi .bash_profile function mkdircd () { mkdir -p "$@" && eval cd ""$$#""; }Now, perform both mkdir and cd at the same time using a single command asshown below: 13

13.
Linux 101 Hacks www.thegeekstuff.com # mkdircd /tmp/subdir1/subdir2/subdir3 [Note: This creates the directory and cd to it automatically] # pwd /tmp/subdir1/subdir2/subdir3Hack 4. Use “cd -” to toggle between the last twodirectoriesYou can toggle between the last two current directories using cd - as shownbelow. # cd /tmp/very/long/directory/structure/that/is/too/deep # cd /tmp/subdir1/subdir2/subdir3 # cd - # pwd /tmp/very/long/directory/structure/that/is/too/deep # cd - # pwd /tmp/subdir1/subdir2/subdir3 # cd - # pwd /tmp/very/long/directory/structure/that/is/too/deepHack 5. Use dirs, pushd and popd to manipulatedirectory stackYou can use directory stack to push directories into it and later pop directoryfrom the stack. Following three commands are used in this example. 14

15.
Linux 101 Hacks www.thegeekstuff.com # dirs /tmp/dir4 /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1 [Note: The first directory (/tmp/dir4) of the dir command output is always the current directory and not the content from the stack.]At this stage, the directory stack contains the following directories: /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1The last directory that was pushed to the stack will be at the top. When youperform popd, it will cd to the top directory entry in the stack and remove itfrom the stack. As shown above, the last directory that was pushed into thestack is /tmp/dir4. So, when we do a popd, it will cd to the /tmp/dir4 andremove it from the directory stack as shown below. # popd # pwd /tmp/dir4 [Note: After the above popd, directory Stack Contains: /tmp/dir3 /tmp/dir2 /tmp/dir1] # popd # pwd /tmp/dir3 [Note: After the above popd, directory Stack Contains: /tmp/dir2 /tmp/dir1] # popd 16

18.
Linux 101 Hacks www.thegeekstuff.com # date +%T%p -s "10:19:53PM"Hack 8. Set Hardware Date and TimeBefore setting the hardware date and time, make sure the OS date and timeis set appropriately as shown in the hack#7.Set the hardware date and time based on the system date as shown below: # hwclock –systohc # hwclock --systohc –utcUse hwclock without any parameter, to view the current hardware date andtime: # hwclockCheck the clock file to verify whether the system is set for UTC: # cat /etc/sysconfig/clock ZONE="America/Los_Angeles" UTC=false ARC=falseHack 9. Display Current Date and Time in a SpecificFormatFollowing are different ways of displaying the current date and time invarious formats: 19

23.
Linux 101 Hacks www.thegeekstuff.comChapter 3: SSH Client CommandsHack 12. Identify SSH Client VersionSometimes it may be necessary to identify the SSH client that you arecurrently running and it’s corresponding version number. Use ssh –V toidentify the version number. Please note that Linux comes with OpenSSH.The following example indicates that this particular system is using OpenSSH: $ ssh -V OpenSSH_3.9p1, OpenSSL 0.9.7a Feb 19 2003The following example indicates that this particular system is using SSH2: $ ssh -V ssh: SSH Secure Shell 3.2.9.1 (non-commercial version) on i686-pc-linux-gnuHack 13. Login to Remote Host using SSHThe First time when you login to a remotehost from a localhost, it will displaythe host key not found message and you can give “yes” to continue. The hostkey of the remote host will be added under .ssh2/hostkeys directory of yourhome directory, as shown below. localhost$ ssh -l jsmith remotehost.example.com Host key not found from database. Key fingerprint: xabie-dezbc-manud-bartd-satsy-limit-nexiu-jambl-title-jarde- tuxum You can get a public key’s fingerprint by running % ssh-keygen -F publickey.pub 24

24.
Linux 101 Hacks www.thegeekstuff.com on the keyfile. Are you sure you want to continue connecting (yes/no)? Yes Host key saved to /home/jsmith/.ssh2/hostkeys/key_22_remotehost.example.com.pub host key for remotehost.example.com, accepted by jsmith Mon May 26 2008 16:06:50 -0700 jsmith@remotehost.example.com password: remotehost.example.com$The Second time when you login to the remote host from the localhost, it willprompt only for the password as the remote host key is already added to theknown hosts list of the ssh client. localhost$ ssh -l jsmith remotehost.example.com jsmith@remotehost.example.com password: remotehost.example.com$For some reason, if the host key of the remote host is changed after youlogged in for the first time, you may get a warning message as shown below.This could be because of various reasons such as: o Sysadmin upgraded/reinstalled the SSH server on the remote host o Someone is doing malicious activity etc.,The best possible action to take before saying “yes” to the message below, isto call your sysadmin and identify why you got the host key changed messageand verify whether it is the correct host key or not. localhost$ ssh -l jsmith remotehost.example.com @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the- 25

25.
Linux 101 Hacks www.thegeekstuff.com middle attack)! It is also possible that the host key has just been changed. Please contact your system administrator. Add correct host key to “/home/jsmith/.ssh2/hostkeys/key_22_remotehost.example.com.pu b” to get rid of this message. Received server key’s fingerprint: xabie-dezbc-manud-bartd-satsy-limit-nexiu-jambl-title-arde- tuxum You can get a public key’s fingerprint by running % ssh-keygen -F publickey.pub on the keyfile. Agent forwarding is disabled to avoid attacks by corrupted servers. Are you sure you want to continue connecting (yes/no)? yes Do you want to change the host key on disk (yes/no)? yes Agent forwarding re-enabled. Host key saved to /home/jsmith/.ssh2/hostkeys/key_22_remotehost.example.com.pub host key for remotehost.example.com, accepted by jsmith Mon May 26 2008 16:17:31 -0700 jsmith @remotehost.example.com’s password: remotehost$Hack 14. Debug SSH Client SessionSometimes it is necessary to view debug messages to troubleshoot any SSHconnection issues. pass -v (lowercase v) option to the ssh as shown below toview the ssh debug messages.Example without SSH client debug message: localhost$ ssh -l jsmith remotehost.example.com warning: Connecting to remotehost.example.com failed: No address associated to the name 26

27.
Linux 101 Hacks www.thegeekstuff.com2. Now you are connected to the remotehost: remotehost$3. To come back to the localhost temporarily, type the escape character ~and Control-Z.When you type ~ you will not see that immediately on the screen until youpress <Control-Z> and press enter. So, on the remotehost in a new line enterthe following key strokes for the below to work: ~<Control-Z> remotehost$ ~^Z [1]+ Stopped ssh -l jsmith remotehost localhost$4. Now you are back to the localhost and the ssh remotehost client sessionruns as a typical UNIX background job, which you can check as shown below: localhost$ jobs [1]+ Stopped ssh -l jsmith remotehost5. You can go back to the remote host ssh without entering the passwordagain by bringing the background ssh remotehost session job to foreground onthe localhost. localhost$ fg %1 ssh -l jsmith remotehost remotehost$ 28

30.
Linux 101 Hacks www.thegeekstuff.comChapter 4: Essential Linux CommandsHack 17. Grep Commandgrep command is used to search files for a specific text. This is incrediblypowerful command with lot of options. Syntax: grep [options] pattern [files]How can I find all lines matching a specific keyword on a file?In this example, grep looks for the text John inside /etc/passwd file anddisplays all the matching lines. # grep John /etc/passwd jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash jdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bashOption -v, will display all the lines except the match. In the example below,it displays all the records from /etc/password that doesnt match John.Note: There are several lines in the /etc/password that doesn’t contain theword John. Only the first line of the output is shown below. # grep -v John /etc/passwd jbourne:x:1084:1084:Jason Bourne:/home/jbourne:/bin/bashHow many lines matched the text pattern in a particular file?In the example below, it displays the total number of lines that contains thetext John in /etc/passwd file. 31

31.
Linux 101 Hacks www.thegeekstuff.com # grep -c John /etc/passwd 2You can also get the total number of lines that did not match the specificpattern by passing option -cv. # grep -cv John /etc/passwd 39How to search a text by ignoring the case?Pass the option -i (ignore case), which will ignore the case while searching. # grep -i john /etc/passwd jsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash jdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bashHow do I search all subdirectories for a text matching a specificpattern?Use option -r (recursive) for this purpose. In the example below, it will searchfor the text "John" by ignoring the case inside all the subdirectories under/home/users.This will display the output in the format of "filename: line that matching thepattern". You can also pass the option -l, which will display only the name ofthe file that matches the pattern. # grep -ri john /home/users /home/users/subdir1/letter.txt:John, Thanks for your contribution. /home/users/name_list.txt:John Smith 32

32.
Linux 101 Hacks www.thegeekstuff.com /home/users/name_list.txt:John Doe # grep -ril john /root /home/users/subdir1/letter.txt /home/users/name_list.txtHack 18. Find Commandfind is frequently used command to find files in the UNIX filesystem based onnumerous conditions. Let us review some practice examples of find command. Syntax: find [pathnames] [conditions]How to find files containing a specific word in its name?The following command looks for all the files under /etc directory with mailin the filename. # find /etc -name "*mail*"How to find all the files greater than certain size?The following command will list all the files in the system greater than100MB. # find / -type f -size +100MHow to find files that are not modified in the last x number of days?The following command will list all the files that were modified more than 60days ago under the current directory. 33

33.
Linux 101 Hacks www.thegeekstuff.com # find . -mtime +60How to find files that are modified in the last x number of days?The following command will list all the files that were modified in the lasttwo days under the current directory. # find . –mtime -2How to delete all the archive files with extension *.tar.gz andgreater than 100MB?Please be careful while executing the following command as you don’t wantto delete the files by mistake. The best practice is to execute the samecommand with ls –l to make sure you know which files will get deleted whenyou execute the command with rm. # find / -type f -name *.tar.gz -size +100M -exec ls -l {} ; # find / -type f -name *.tar.gz -size +100M -exec rm -f {} ;How to archive all the files that are not modified in the last xnumber of days?The following command finds all the files not modified in the last 60 daysunder /home/jsmith directory and creates an archive files under /tmp in theformat of ddmmyyyy_archive.tar. # find /home/jsmith -type f -mtime +60 | xargs tar -cvf /tmp/`date +%d%m%Y_archive.tar`On a side note, you can perform lot of file related activities (including findingfiles) using midnight commander GUI, a powerful text based file manager forUnix. 34

34.
Linux 101 Hacks www.thegeekstuff.comHack 19. Suppress Standard Output and ErrorMessageSometime while debugging a shell script, you may not want to see either thestandard output or standard error message. Use /dev/null as shown below forsuppressing the output.Suppress standard output using > /dev/nullThis will be very helpful when you are debugging shell scripts, where youdon’t want to display the echo statement and interested in only looking atthe error messages. # cat file.txt > /dev/null # ./shell-script.sh > /dev/nullSuppress standard error using 2> /dev/nullThis is also helpful when you are interested in viewing only the standardoutput and don’t want to view the error messages. # cat invalid-file-name.txt 2> /dev/null # ./shell-script.sh 2> /dev/nullHack 20. Join CommandJoin command combines lines from two files based on a common field.In the example below, we have two files – employee.txt and salary.txt. Bothhave employee-id as common field. So, we can use join command to combine 35

36.
Linux 101 Hacks www.thegeekstuff.com 400 ASHOK SHARMAConvert a file to all lower-case $ cat department.txt 100 FINANCE 200 MARKETING 300 PRODUCT DEVELOPMENT 400 SALES $ tr A-Z a-z < department.txt 100 finance 200 marketing 300 product development 400 salesHack 22. Xargs Commandxargs is a very powerful command that takes output of a command and pass itas argument of another command. Following are some practical examples onhow to use xargs effectively.1. When you are trying to delete too many files using rm, you may get errormessage: /bin/rm Argument list too long – Linux. Use xargs to avoid thisproblem. find ~ -name ‘*.log’ -print0 | xargs -0 rm -f2. Get a list of all the *.conf file under /etc/. There are different ways to getthe same result. Following example is only to demonstrate the use of xargs.The output of the find command in this example is passed to the ls –l one byone using xargs. 37

37.
Linux 101 Hacks www.thegeekstuff.com # find /etc -name "*.conf" | xargs ls –l3. If you have a file with list of URLs that you would like to download, you canuse xargs as shown below. # cat url-list.txt | xargs wget –c4. Find out all the jpg images and archive it. # find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz5. Copy all the images to an external hard-drive. # ls *.jpg | xargs -n1 -i cp {} /external-hard- drive/directoryHack 23. Sort CommandSort command sorts the lines of a text file. Following are several practicalexamples on how to use the sort command based on the following sample textfile that has employee information in the format: employee_name:employee_id:department_name. $ cat names.txt Emma Thomas:100:Marketing Alex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales 38

40.
Linux 101 Hacks www.thegeekstuff.comHack 24. Uniq CommandUniq command is mostly used in combination with sort command, as uniqremoves duplicates only from a sorted file. i.e In order for uniq to work, allthe duplicate entries should be in the adjacent lines. Following are somecommon examples.1. When you have an employee file with duplicate entries, you can do thefollowing to remove duplicates. $ sort namesd.txt | uniq $ sort –u namesd.txt2. If you want to know how many lines are duplicates, do the following. Thefirst field in the following examples indicates how many duplicates wherefound for that particular line. So, in this example the lines beginning withAlex and Emma were found twice in the namesd.txt file. $ sort namesd.txt | uniq –c 2 Alex Jason:200:Sales 2 Emma Thomas:100:Marketing 1 Madison Randy:300:Product Development 1 Nisha Singh:500:Sales 1 Sanjay Gupta:400:Support3. The following displays only the entries that are duplicates. $ sort namesd.txt | uniq –cd 2 Alex Jason:200:Sales 2 Emma Thomas:100:Marketing 41

43.
Linux 101 Hacks www.thegeekstuff.comDisplay the status of the filesystem using option –f $ stat -f / File: "/" ID: 0 Namelen: 255 Type: ext2/ext3 Blocks: Total: 2579457 Free: 2008027 Available: 1876998 Size: 4096 Inodes: Total: 1310720 Free: 1215892Hack 27. Diff Commanddiff command compares two different files and reports the difference. Theoutput is very cryptic and not straight forward to read. Syntax: diff [options] file1 file2What was modified in my new file when compare to my old file?The option -w in the diff command will ignore the white space whileperforming the comparison.In the following diff output: o The lines above ---, indicates the changes happened in first file in the diff command (i.e name_list.txt). o The lines below ---, indicates the changes happened to the second file in the diff command (i.e name_list_new.txt). The lines that belong to the first file starts with < and the lines of second file starts with >. # diff -w name_list.txt name_list_new.txt 44

44.
Linux 101 Hacks www.thegeekstuff.com 2c2,3 < John Doe --- > John M Doe > Jason BourneHack 28. Display total connect time of usersAc command will display the statistics about the user’s connect time.Connect time for the current logged in userWith the option –d, it will break down the output for the individual days. Inthis example, I’ve been logged in to the system for more than 6 hours today.On Dec 1st, I was logged in for about 1 hour. $ ac –d Dec 1 total 1.08 Dec 2 total 0.99 Dec 3 total 3.39 Dec 4 total 4.50 Today total 6.10Connect time for all the usersTo display connect time for all the users use –p as shown below. Please notethat this indicates the cumulative connect time for the individual users. $ ac -p john 3.64 madison 0.06 sanjay 88.17 nisha 105.92 45

46.
Linux 101 Hacks www.thegeekstuff.comChapter 5: PS1, PS2, PS3, PS4 andPROMPT_COMMANDHack 29. PS1 - Default Interaction PromptThe default interactive prompt on your Linux can be modified as shown belowto something useful and informative. In the following example, the defaultPS1 was “s-v$”, which displays the shell name and the version number. Letus change this default behavior to display the username, hostname andcurrent working directory name as shown below. -bash-3.2$ export PS1="u@h w> " ramesh@dev-db ~> cd /etc/mail ramesh@dev-db /etc/mail> [Note: Prompt changed to "username@hostname current- dir>" format]Following PS1 codes are used in this example: o u – Username o h – Hostname o w - Full pathname of current directory. Please note that when you are in the home directory, this will display only ~ as shown aboveNote that there is a space at the end in the value of PS1. Personally, I prefera space at the end of the prompt for better readability.Make this setting permanent by adding export PS1=”u@h w> ” to either.bash_profile (or) .bashrc as shown below. 47

51.
Linux 101 Hacks www.thegeekstuff.com ../ps4.sh.4+ wc -l 243 ../ps4.sh.5+ du -sh /home/ramesh 48K /home/ramesh [Note: This displays the modified "{script-name}.{line- number}+" while tracing the output using set -x]Hack 33. PROMPT_COMMANDBash shell executes the content of the PROMPT_COMMAND just beforedisplaying the PS1 variable. ramesh@dev-db ~> export PROMPT_COMMAND="date +%k:%m:%S" 22:08:42 ramesh@dev-db ~> [Note: This displays the PROMPT_COMMAND and PS1 output on different lines]If you want to display the value of PROMPT_COMMAND in the same line as thePS1, use the echo -n as shown below. ramesh@dev-db ~> export PROMPT_COMMAND="echo -n [$(date +%k:%m:%S)]" [22:08:51]ramesh@dev-db ~> [Note: This displays the PROMPT_COMMAND and PS1 output on the same line] 52

52.
Linux 101 Hacks www.thegeekstuff.comChapter 6: Colorful and Functional ShellPrompt Using PS1Hack 34. Display username, hostname and basenameof directory in the promptThe PS1 in this example displays following three information in the prompt: o u – Username o h – Hostname o W – Base name of the current working directory -bash-3.2$ export PS1="u@h W> " ramesh@dev-db ~> cd /etc/mail ramesh@dev-db mail>Hack 35. Display current time in the promptIn the PS1 environment variable, you can directly execute any Linuxcommand, by specifying in the format $(linux_command). In the followingexample, the command $(date) is executed to display the current time insidethe prompt. ramesh@dev-db ~> export PS1="u@h [$(date +%k:%m:%S)]> " ramesh@dev-db [11:09:56]> 53

53.
Linux 101 Hacks www.thegeekstuff.comYou can also use t to display the current time in the hh:mm:ss format asshown below: ramesh@dev-db ~> export PS1="u@h [t]> " ramesh@dev-db [12:42:55]>You can also use @ to display the current time in 12-hour am/pm format asshown below: ramesh@dev-db ~> export PS1="[@] u@h> " [04:12 PM] ramesh@dev-db>Hack 36. Display output of any command in thepromptYou can display output of any Linux command in the prompt. The followingexample displays three items separated by | (pipe) in the command prompt: o !: The history number of the command o h: hostname o $kernel_version: The output of the uname -r command from $kernel_version variable o $?: Status of the last command ramesh@dev-db ~> kernel_version=$(uname -r) ramesh@dev-db ~> export PS1="!|h|$kernel_version|$?> " 473|dev-db|2.6.25-14.fc9.i686|0> 54

59.
Linux 101 Hacks www.thegeekstuff.com o h the hostname up to the first part o H the hostname o j the number of jobs currently managed by the shell o l the basename of the shell’s terminal device name o n newline o r carriage return o s the name of the shell, the basename of $0 (the portion following the final slash) o t the current time in 24-hour HH:MM:SS format o T the current time in 12-hour HH:MM:SS format o @ the current time in 12-hour am/pm format o A the current time in 24-hour HH:MM format o u the username of the current user o v the version of bash (e.g., 2.00) o V the release of bash, version + patch level (e.g., 2.00.0) o w the current working directory, with $HOME abbreviated with a tilde o W the basename of the current working directory, with $HOME abbreviated with a tilde o ! the history number of this command o # the command number of this command o $ if the effective UID is 0, a #, otherwise a $ o nnn the character corresponding to the octal number nnn o a backslash o [ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt 60

67.
Linux 101 Hacks www.thegeekstuff.comHow do I view all the files inside the tar archive?Option t will display all the files from the tar archive. # tar tvf /tmp/my_home_directory.tarHow do I extract all the files from a tar archive?Option x will extract the files from the tar archive as shown below. This willextract the content to the current directory location from where thecommand is executed. # tar xvf /tmp/my_home_directory.tarHow do I extract tar.gz files to a specific directory? # tar xvfz /tmp/my_home_directory.tar.gz –C /home/rameshHack 49. Combine gzip, bzip2 with tarHow to use gzip with tar?Add option z to the tar command when dealing with tar.gz compressed file. # tar cvfz /tmp/my_home_directory.tar.gz /home/jsmith # tar xvfz /tmp/my_home_directory.tar.gz # tar tvfz /tmp/my_home_directory.tar.gzNote: Using gzip is faster when compared to bzip2. 68

69.
Linux 101 Hacks www.thegeekstuff.comChapter 8: Command Line HistoryWhen you are using Linux command line frequently, using the historyeffectively can be a major productivity boost. In fact, once you havemastered the 15 examples that I’ve provided here, you’ll find using commandline more enjoyable and fun.Hack 50. Display TIMESTAMP in history usingHISTTIMEFORMATTypically when you type history from command line, it displays thecommand# and the command. For auditing purpose, it may be beneficial todisplay the timestamp along with the command as shown below. # export HISTTIMEFORMAT=’%F %T ‘ # history | more 1 2008-08-05 19:02:39 service network restart 2 2008-08-05 19:02:39 exit 3 2008-08-05 19:02:39 id 4 2008-08-05 19:02:39 cat /etc/redhat-releaseNote: You can also setup the following alias to view the recent historycommands. alias h1=history 10 alias h2=history 20 alias h3=history 30Hack 51. Search the history using Control+RI strongly believe that this may be your most frequently used feature ofhistory. When you’ve already executed a very long command, you can simply 70

70.
Linux 101 Hacks www.thegeekstuff.comsearch history using a keyword and re-execute the same command withouthaving to type it fully. Press Control+R and type the keyword.In the following example, I searched for red, which displayed the previouscommand “cat /etc/redhat-release” in the history that contained the wordred. # [Note: Press Ctrl+R from the command prompt, which will display the reverse-i-search prompt as shown below] (reverse-i-search)`red‘: cat /etc/redhat-release [Note: Press enter when you see your command, which will execute the command from the history] # cat /etc/redhat-release Fedora release 9 (Sulphur)Sometimes you want to edit a command from history before executing it. Fore.g. you can search for httpd, which will display service httpd stop from thecommand history, select this command and change the stop to start and re-execute it again as shown below. # [Note: Press Ctrl+R from the command prompt, which will display the reverse-i-search prompt] (reverse-i-search)`httpd‘: service httpd stop [Note: Press either left arrow or right arrow key when you see your command, which will display the command for you to edit, before executing it] # service httpd start 71

71.
Linux 101 Hacks www.thegeekstuff.comHack 52. Repeat previous command quickly using 4different methodsSometime you may end up repeating the previous commands for variousreasons. Following are the 4 different ways to repeat the last executedcommand. 1. Use the up arrow to view the previous command and press enter to execute it. 2. Type !! and press enter from the command line 3. Type !-1 and press enter from the command line. 4. Press Control+P will display the previous command, press enter to execute itHack 53. Execute a specific command from historyIn the following example, If you want to repeat the command #4, execute !4as shown below. # history | more 1 service network restart 2 exit 3 id 4 cat /etc/redhat-release # !4 cat /etc/redhat-release Fedora release 9 (Sulphur) 72

72.
Linux 101 Hacks www.thegeekstuff.comHack 54. Execute previous command that starts witha specific wordType ! followed by the starting few letters of the command that you wouldlike to re-execute. In the following example, typing !ps and enter, executedthe previous command starting with ps, which is ‘ps aux | grep yp’. # !ps ps aux | grep yp root 16947 0.0 0.1 36516 1264 ? Sl 13:10 0:00 ypbind root 17503 0.0 0.0 4124 740 pts/0 S+ 19:19 0:00 grep ypHack 55. Control the total number of lines in thehistory using HISTSIZEAppend the following two lines to the .bash_profile and relogin to the bashshell again to see the change. In this example, only 450 command will bestored in the bash history. # vi ~/.bash_profile HISTSIZE=450 HISTFILESIZE=450Hack 56. Change the history file name using HISTFILEBy default, history is stored in ~/.bash_history file. Add the following line tothe .bash_profile and relogin to the bash shell, to store the history commandin .commandline_warrior file instead of .bash_history file. I’m yet to figureout a practical use for this. I can see this getting used when you want to trackcommands executed from different terminals using different history filename. 73

75.
Linux 101 Hacks www.thegeekstuff.comHack 59. Force history not to remember a particularcommand using HISTCONTROLWhen you execute a command, you can instruct history to ignore thecommand by setting HISTCONTROL to ignorespace AND typing a space in frontof the command as shown below. I can see lot of junior sysadmins gettingexcited about this, as they can hide a command from the history.It is good to understand how ignorespace works. But, as a best practice, don’thide purposefully anything from history. # export HISTCONTROL=ignorespace # ls –ltr # pwd # service httpd stop [Note: There is a space at the beginning of service, to ignore this command from history] # history | tail -3 67 ls –ltr 68 pwd 69 history | tail -3Hack 60. Clear all the previous history using option -cSometime you may want to clear all the previous history. However you maystill want to keep the history moving forward. # history -c 76

76.
Linux 101 Hacks www.thegeekstuff.comHack 61. Substitute words from history commandsWhen you are searching through history, you may want to execute a differentcommand but use the same parameter from the command that you’ve justsearched.In the example below, the !!:$ next to the vi command gets the argumentfrom the previous command to the current command. # ls anaconda-ks.cfg anaconda-ks.cfg # vi !!:$ vi anaconda-ks.cfgIn the example below, the !^ next to the vi command gets the first argumentfrom the previous command (i.e cp command) to the current command (i.e vicommand). # cp anaconda-ks.cfg anaconda-ks.cfg.bak anaconda-ks.cfg # vi !^ vi anaconda-ks.cfgHack 62. Substitute a specific argument for a specificcommandIn the example below, !cp:2 searches for the previous command in historythat starts with cp and takes the second argument of cp and substitutes it forthe ls -l command as shown below. 77

77.
Linux 101 Hacks www.thegeekstuff.com # cp ~/longname.txt /really/a/very/long/path/long- filename.txt # ls -l !cp:2 ls -l /really/a/very/long/path/long-filename.txtIn the example below, !cp:$ searches for the previous command in historythat starts with cp and takes the last argument (in this case, which is also thesecond argument as shown above) of cp and substitutes it for the ls -lcommand as shown below. # ls -l !cp:$ ls -l /really/a/very/long/path/long-filename.txtHack 63. Disable the usage of history using HISTSIZEIf you want to disable history all together and don’t want bash shell toremember the commands you’ve typed, set the HISTSIZE to 0 as shown below. # export HISTSIZE=0 # history # [Note: History did not display anything]Hack 64. Ignore specific commands from the historyusing HISTIGNORESometimes you may not want to clutter your history with basic commandssuch as pwd and ls. Use HISTIGNORE to specify all the commands that youwant to ignore from the history. 78

78.
Linux 101 Hacks www.thegeekstuff.comPlease note that adding ls to the HISTIGNORE ignores only ls and not ls -l. So,you have to provide the exact command that you would like to ignore fromthe history. # export HISTIGNORE=”pwd:ls:ls –ltr:” # pwd # ls # ls -ltr # service httpd stop # history | tail -3 79 export HISTIGNORE=”pwd:ls:ls -ltr:” 80 service httpd stop 81 history [Note: History did not display pwd and ls] 79

79.
Linux 101 Hacks www.thegeekstuff.comChapter 9: System Administration TasksHack 65. Partition using fdiskAfter you’ve installed brand new disks on your server, you have to use toolslike fdisk to partition it accordingly.Following are the 5 typical actions (commands) that you can execute insidefdisk. o n – New Partition creation o d – Delete an existing partition o p - Print Partition Table o w – Write the changes to the partition table. i.e save. o q – Quit the fdisk utilityCreate a partitionIn the following example, I created a /dev/sda1 primary partition. # fdisk /dev/sda Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel Building a new DOS disklabel. Changes will remain in memory only, until you decide to write them. After that, of course, the previous content wont be recoverable. The number of cylinders for this disk is set to 34893. There is nothing wrong with that, but this is larger than 1024, and could in certain setups cause problems with: 80