Pete's Linux Advent Calendar 2007
The 8th day
Stupid Shell Tricks or What to do in an emergency
What happens when you execute this command: /bin/ls*
(including the "*")? On my system it gives:
/bin/lsmod /bin/lsmod.modutils /bin/lspci
And you probably know what has happened. The Shell expanded the
pattern /bin/ls* to
/bin/ls /bin/lsmod /bin/lsmod.modutils /bin/lspci and
executed this resulting command line. How can that be useful?
Imagine a situation where you have no more or less
(pun indendet :-) nor vi nor ls but you
are running bash. Maybe somebody has deleted these
files. How can you substitute these commands by only using
shell builtins?
- ls
- just type
echo *
- cat
- type:
while read; do echo "$REPLY"; done < filename
- append a line
echo new line >> filename
- prepend a line
-
oldfile=$(while read; do echo "$REPLY"; done < filename)
{ echo new line ; echo "$oldfile" ; } > filename
- modify a line in a file
- Say, you want to modify the IP address of an entry in
/etc/hosts. Let us assume you want to replace
the address 192.168.0.1 to 192.168.0.2:
modified_hosts=$(while read ip rest; do
if [ "$ip" = 192.168.0.1 ]; then
ip=192.168.0.2
fi
echo -e "$ip\t$rest"
done < /etc/hosts)
echo "$modified_hosts" > /etc/hosts
Note that this is not very strict in preserving whitespace, but it does
what we wanted.