Linux Shell Tips and Tricks
Overview
Redirecting STDERR
Redirects stderr to stdout.
program 2>&1Redirect both stdout and sterr to log.txt.
program >log.txt 2>&1 log.txt
Escaped Characters
#!/bin/bash" echo "\v\v\v\v" # Prints \v\v\v\v echo -e "\v\v\v\v" # Prints 4 vertical tabs. echo -e "\042" # Prints " (quote, octal ASCII character 42). echo $'\n' # Prints line feed echo $'\a' echo $'\t \042 \t' # Quote (") framed by tabs. quote=$'\042' # " assigned to a variable. echo "$quote This is a quoted string, $quote and this lies outside the quotes." triple_underline=$'\137\137\137' # 137 is octal ASCII code for "_". echo "$triple_underline UNDERLINE $triple_underline" ABC=$'\101\102\103\010' # 101, 102, 103 are octal A, B, C. echo $ABC escape=$'\033' # 033 is octal for escape. echo "\"escape\" echoes as $escape"
Echoing Weird Variables
#!/bin/bash" var="'(]\\{}\$\"" echo $var # '(]\{}$" echo "$var" # '(]\{}$" Doesn't make a difference. IFS='\' echo $var # '(]\{}$" \ converted to space. echo "$var" # '(] {}$" # Examples above supplied by S.C. exit 0Single quotes (' ') operate similarly to double quotes, but do not permit referencing variables, since the special meaning of $ is turned off. Within single quotes, every special character except ' gets interpreted literally. Consider single quotes ("full quoting") to be a stricter method of quoting than double quotes ("partial quoting").
Showing Directory/Machine Name In The Title Bar Of Your Shell Windows
To show the current directory, add the following three lines to your $HOME/.cshrc-linux-$user file:
alias cd ' chdir \!* && header `dirs` ' alias header ' echo -n "\033]2;\!*\007\033]1;\007" ' header `dirs`Now open a new window, or manually execute source $HOME/.cshrc-linux-$user. You should now see the current directory in the title bar of the window.To show the machine as well as the directory in machine:directory format, use the following three lines instead:
alias cd ' chdir \!* && header `hostname`":"`dirs` ' alias header ' echo -n "\033]2;\!*\007\033]1;\007" ' header `hostname`":"`dirs`
Modifying The Colors In Directory Listings
You will notice that there are default colors in directory listings for certain types of files; executables are green, directories are dark blue, symbolic links are light blue. This is accomplished by the line alias ls "ls -CF --color=tty" in the system /etc/csh.cshrc file.
If you don't want any colors at all, either place the line "unalias ls" in your $HOME/.cshrc-linux-$user file (create the file if you don't have it), or redefine an alias for ls to list things the way you want, e.g. alias ls "ls -F"
To modify the colors, you need to set the LS_COLORS environment variable. for more details.
Customizing Your Prompt in Linux
Execute the following commands to give the following prompts:Comands below will colorize your prompt. Try one of the following:
set prompt="%m:%{^[[36;1m%}%/%{^[[0m%}> " set prompt="%m:%{^[[34;1m%}%/%{^[[0m%}> " set prompt="%m:%{^[[31;1m%}%/%{^[[0m%}> " (Make the colors a little darker by changing the ;1m to ;3m) set prompt="%m$ " set prompt="%n@%m: " set prompt="%n@%{^[[34;1m%}%m%{^[[0m%} "Place the appropriate command in your .cshrc-linux-$user file (create the file if you don't already have it).
What "dot" files do the various shells use (configuration files)
Although this may not be a complete listing, this provides the majority of information. csh Some versions have system-wide .cshrc and .login files. Every version puts them in different places. Start-up (in this order): .cshrc - always; unless the -f option is used. .login - login shells. Upon termination: .logout - login shells. Others: .history - saves the history (based on $savehist). tcsh Start-up (in this order): /etc/csh.cshrc - always. /etc/csh.login - login shells. .tcshrc - always. .cshrc - if no .tcshrc was present. .login - login shells Upon termination: .logout - login shells. Others: .history - saves the history (based on $savehist). .cshdirs - saves the directory stack. sh Start-up (in this order): /etc/profile - login shells. .profile - login shells. Upon termination: any command (or script) specified using the command: trap "command" 0 ksh Start-up (in this order): /etc/profile - login shells. .profile - login shells; unless the -p option is used. $ENV - always, if it is set; unless the -p option is used. /etc/suid_profile - when the -p option is used. Upon termination: any command (or script) specified using the command: trap "command" 0 bash Start-up (in this order): /etc/profile - login shells. .bash_profile - login shells. .profile - login if no .bash_profile is present. .bashrc - interactive non-login shells. $ENV - always, if it is set. Upon termination: .bash_logout - login shells. Others: .inputrc - Readline initialization. zsh Start-up (in this order): .zshenv - always, unless -f is specified. .zprofile - login shells. .zshrc - interactive shells, unless -f is specified. .zlogin - login shells. Upon termination: .zlogout - login shells. rc Start-up: .rcrc - login shells
Find out which user or process has a file open or is using a particular file system (so that you can unmount it?)
Use fuser (system V), fstat (BSD), ofiles (public domain) or pff (public domain). These programs will tell you various things about processes using particular files.
A port of the 4.3 BSD fstat to Dynix, SunOS and Ultrix can be found in archives of comp.sources.unix, volume 18.
pff is part of the kstuff package, and works on quite a few systems. Instructions for obtaining kstuff are provided in question 3.10.
You can also use lsof to list open files.
If you are unable to unmount a file system for which above tools do not report any open files make sure that the file system that you are trying to unmount does not contain any active mount points (df(1)).
How to rename hidden files (.foo to .bar)
C Shell: foreach f ( *.foo ) set base=`basename $f .foo` mv $f $base.bar end Bourne Shell: for f in *.foo; do base=`basename $f .foo` mv $f $base.bar done Some shells have their own variable substitution features, so instead of using "basename", you can use simpler loops like: C Shell: foreach f ( *.foo ) mv $f $f:r.bar end Korn Shell: for f in *.foo; do mv $f ${f%foo}bar done If you don't have "basename" or want to do something like renaming foo.* to bar.*, you can use something like "sed" to strip apart the original file name in other ways, but the general looping idea is the same. You can also convert file names into "mv" commands with 'sed', and hand the commands off to "sh" for execution. Try ls -d *.foo | sed -e 's/.*/mv & &/' -e 's/foo$/bar/' | sh
Removing a file whose name begins with a "-"
rm ./-filename
How to find which libraries a program requires?
To find out which shared libraries a program requires, type
ldd `which program`
How to find out what process is eating the most memory?
ps -aux | sort +4n
Customizing your directory colors (linux)
All you need to do is add the following line to your /etc/bashrc file.eval `dircolors /etc/DIR_COLORS`And then all of the color configuration can be found in the file /etc/DIR_COLORS
HOW TO EXECUTE A TEXT OR BINARY FILE
You can try the following builtin command:
source file_name
To execute file directly make it executable first:
chmod +rx file_nameNow execute it with absolute or relative path such as:
/home/user1/file_name
./file_name
Or with shell:
ksh file_name
Some examples on using stty command:
stty 9640 # set the terminal bit rate to 9640 bps stty rows 30 columns 75 # set the terminal window size to 30 rows and # 75 columns stty erase# set backspace button stty erase \^H # set backspace button stty erase kill # set CTRL+X as your kill character instead of @ stty erase kill \^X # set CTRL+X as your kill character instead of @ stty eof # set CTRL+C as end-of-file character stty eof \^C # set CTRL+C as end-of-file character stty ek # set reset your erase and kill character back # to # and @ stty -a # check your terminal settings stty sape # set terminal to use the most common options in # case of troubles
Show working directory in command prompt
PS1="\$PWD $ " If you are using csh: set prompt="${cwd:t}%"
Some examples on using date command:
date # shows corrent date and time date DDMMhhmmYY # sets current date and time
Some examples on using ls command:
ls # lists contents in current dir ls -a # lists contents in current dir including hidden files ls -l # lists contents in current dir in long form ls -h # lists contents in current dir with sizes in kb/mb (linux)
Some examples on using df/bdf command:
bdf # show mounted filesystems df # show mounted filesystems (linux) df -h # show mounted filesystems with sizes in kb/mb (linux)
Some examples on using more command:
more file_name # lists contents of a file more * # lists contents of all files in current directory
Some examples on using rm command:
rm file # removes file rm -R -i dir # interractively removes directory recursively # (including hidden and sistem files) rm -R -f dir # removes directory with option force (noninterractive) rm -R -f * # irreversably removes everything on the current path
Some examples on using cd command:
cd # puts you into your home directory cd / # puts you to the root directory cd - # puts you to the directory last accessed cd ~/data # puts you to the directory data in your home directory cd ../dir2 # puts you from the current subdirectory to another # (dir2) at the same directory level
Finding Out More Terminal Settings
stty -a
Resetting Terminal Characteristics
Try some of the following clear tput clear tput reset tput init reset stty sane eval `resize`
Saving Your Terminal Characteristics
stty -g > $HOME/.stty
Restoring Saved Terminal Characteristics
stty `cat $HOME/.stty`
Define Default Login Shell
chsh sh
Define Shell Command-Line Editing Mode
Use Emacs or vi in command line to edit commands>Emacs editing mode: set -o emacs Vi editing mode: set -o vi
Show Last Entries in Command History List
fc -l
Show Total Command History List
fc -l 1 or history
Saving Shell Output Into File
script ... commands ... exitA file containing everything printed on the console will now be typescript
Show Jobs
jobs
Kill All My Jobs Except This One
kill -TERM -1
Kill More Jobs At the Same Time
On System V UNIXes:ps -ef | awk '/pattern/ print $2 ' | xargs kill -9
Show status of running jobs
On System V UNIXes:ps -elf | cut -c 5-15,84-
Show Last 100 Commands
fc -l -100
Stop Background Job
Automatically stop background jobs if they write to screentty -tostop or kill %job_number
Displaying Most Active Processes
On BSD UNIXes: ps -aux | head -5 top yamm ps -aux | sort +4n ps -aux | sort +5n
Displaying All Processes
On System V UNIXes: ps -ef On BSD UNIXes: ps -aux
Displaying All Zombie Processes
On System V UNIXes:ps -el | grep " Z "
Displaying All Running Processes
ps -el | grep " R "
Timing Programs
time program arguments
Checking System Load Time
uptime
Be Nice To Other Users With Time Consuming Job
Run a command at non-default prioritynice f77 -o test test.f > f77.out
Changing Job Priority
Example:renice 5 -p pid
CHANGE PERMISSIONS ON ALL FILES IN DIRECTORY
chmod -R 755 dir_name
WHEN THE SPECIFIC USER WAS LAST LOGGED IN ?
To see all logging informations for specific user try the following:last user_name |more