Linux exercises for examination - Updated !!

Day la 9 bai ma minh co de bai … con cac bai con lai…hoac co cho nao ko hieu thi cac ban cu comment thac mac cho minh hoac wa YM! billyduc1987 …. Chuc moi nguoi thi tot ^^

Vi co 10 bai nhung bai 4 va bai 9 bi trung nen mat 1 bai…ai co bai do thi send cho D, bai 8 va bai 10 phai chay = quyen root, 2 bai nay billy chua chay thu lai trong F9 vi may moi cai lai…mac cong xoa user…ban nao co may ao thi chay thu lai … va bao loi cho D biet de fix loi…giai thuat thi OK do !

1. Viết chương trình in ra n dòng như sau: (n truyền tham số; n=1..30).
VD: n=5
11111
22222
33333
44444
55555

Cần phải kiễm tra:
+ Nếu n < 1 thì báo lỗi và thoát chương trình.
+ Nếu n > 30 thì báo lỗi và thoát chương trình.

echo -n “Nhap n = “
read n
if [ $n -le 1 -o $n -ge 30 ]
then
echo “Error give n between (1 - 30)”
exit 1
else
for ((i=1;i<=n;i++))
do
for ((j=1;j<=n;j++))
do
echo -n “$i “
done
echo
done
fi

2. Hãy viết chương trình xuất ra trắng đen như bàn cờ quốc tế n x n (n nhập từ bàn phím)
Phần kiễm tra:
Không cần phải kiễm tra n nhập vào như thế nào.
VD: n được nhập = 9

echo -n “Nhap n = “
read n
echo
t=0
for((i=1;i<n;i++))
do
t=`expr $i % 2`
if [ $t -eq 1 ]
then
for((j=1;j<n;j++))
do
echo -e -n “33[47m "
echo -e -n "33[40m "
done
echo -e "33[0m "
else
for((j=1;j<n;j++))
do
echo -e -n "33[40m "
echo -e -n "33[47m "
done
echo -e "33[0m "
fi
done
echo -e "33[0m "

3. Hãy cho biết giá trị của n! (n truyền từ tham số n >= 0) VD:
Nếu n=0 ==> n!=1
Nếu n=1 ==> n!=1
Nếu n=2 ==> n!=2
Nếu n=3 ==> n!=6
Nếu n=4 ==> n!=24
...

Cần phải kiễm tra:
+ Nếu không có tham số nào thì báo lỗi và thoát chương trình.
+ Nếu n < 0 thì báo lỗi và thoát chương trình.

echo -n "Nhap n giai thua = "
read n
if [ $n -le 1 ]
then
echo “n! = 1″
else
gt=1
i=1
while [ $i -le $n ]
do
gt=`expr $gt \* $i`
i=`expr $i + 1`
done
echo “n! = $gt”
fi

5. Sử dụng vòng lập for để in “1. Hello Word” n lần (n = 0..100) . với n truyền tham số.
Cần phải kiễm tra:
+ Nếu n < 0 thì báo lỗi và thoát chương trình.
+ Nếu n > 100 thì báo lỗi và thoát chương trình.

echo -n “Nhap n = “
read n
if [ $n -gt 100 -o $n -lt 0 ]
then
echo “Error…Give number between 0 -> 100 please”
exit 1
else
for ((i=1;i<=n;i++))
do
echo “$i. Hello World”
done
fi

6. Viết chương trình nhận vào 2 số a, b. Cho biết tích 2 số a * b là bao nhiêu.
Cần phải kiễm tra:
+ Nếu không đủ tham số thì báo lỗi và thoát chương trình.

if [ $# -lt 2 -o $# -gt 2 ]
then
echo “Error…give 2 number for multiply”
exit 1
else
echo “Tich $1 * $2 = `expr $1 \* $2`”
fi
7. Viết chương trình in bảng cửu chương n (n = 1..10) (n truyền từ tham số. Nếu không có tham số nào thì default n = 2 Nếu có tham số nhưng không thuộc từ 1..10 thì báo lỗi và thoát chương trình.
Cần phải kiễm tra:
+ Nếu n < 1 thì báo lỗi và thoát chương trình.
+ Nếu n > 10 thì báo lỗi và thoát chương trình.

if [ $# -eq 0 ]
then
n=2
elif [ $# -gt 1 ]
then
echo “Error…Give 1 number for multiply number”
exit 1
else
n=$1
fi
if [ $n -lt 1 -o $n -gt 10 ]
then
echo “hehe…we give u only 1 to 10″
exit 1
else
for((i=1;i<=10;i++))
do
echo “$n * $i = `expr $n \* $i`”
done
fi

8. Viết chương trình:
+ tạo các thư mục /g1
/g2
/g1/u1
/g1/u2

+ Tạo 2 user (user1 và user2) và 2 nhóm (g1 và g2).
+ Cấp quyền cho user1 toàn quyền trên /g1/u1
+ Home dir của user2 là /g1/u2
+ nhóm g2 toàn quyền trên thư mục /g2
+ Nhóm khác chỉ đọc trên thư mục /g2

Phần kiễm tra:
+ Không cần phải kiểm tra gì cả.

mkdir /home/g1
mkdir /home/g1/u1
mkdir /home/g2
mkdir /home/g1/u2
groupadd g1
groupadd g2
useradd -p hihi -d /home/g1/u1 -g g1 u1
chown u1 /home/g1/u1
useradd -p hehe -d /home/g1/u2 -g g1 u2
chgrp g2 /home/g2
chmod 744 /home/g2

chay bai 8 bang quyen root (su -) ./bai8
9. Viết chương trình nhận vào 1 tham số tên của bạn và 1 tham số đường dẫn tên file, rồi xuất ra màn hình nhiều dòng của file , mỗi dòng đều có cấu trúc: : nội dung dòng i”. Với được truyền từ tham số đầu tiên, tên file được truyền tiếp theo.
Cần phải kiễm tra:
+ Nếu thiếu 1 trong những tham số thì báo lỗi và thoát chương trình.
+ Nếu file không tồn tại báo lỗi và thoát chương trình.

if [ $# -lt 2 -o $# -gt 2 ]
then
echo “Error…Give $1 = yourname … give $2 = yourpath”
exit 1
else
name=$1
path=$2
while read linei
do
echo “$linei — $name — $path”
done < $path
fi

./bai9 yourname ./yourpath          ex: ./bai9 billyduc ./text.txt

text.txt

haha
hehe
hihi
hoho
huhu

10. Tạo n user va n/2 nhóm (n nhập từ bàn phím với n > 0 và chẳn): user1 user2 : nhom1; user3, user4: nhom 2.

Cần phải kiễm tra:
+ Nếu không có tham số nào thì báo lỗi và thoát chương trình.
+ Nếu n <= 0 thì báo lỗi và thoát chương trình.

if [ $# -ne 1 ]
then
echo “Error…Give 1 arguments : an even number”
exit 1
else
n=$1
t=`expr n % 2`
if [ $n -lt 1 -a $t -eq 1 ]
then
echo “Error..give even number”
exit 1
else
for((i=1;i<=t;i++))
do
groupadd g$i
j=`expr $i * 2 - 1`
useradd -g g$i u$j
j=`expr $i * 2`
useradd -g g$i u$j
done
done
fi
fi

The End !!
Updated - 2 bai cuoi
# sort danh sach gom nhieu truong khac nhau
if [ ! -e $1 ]
then
echo “File $1 not found”
exit 1
else
tr -s ‘\t’ ‘ ‘ /tmp/sortfile.$$#
while read dong
do
sotu=`echo $dong | wc -w`
holot=`echo $dong | cut -d : -f1`
ten=`echo $dong | cut -d : -f2`
misc=`echo $dong |cut -d : -f3-$sotu`
echo “$ten : $holot : $misc” >> /tmp/sortfile.$$
done
sort /tmp/sortfile.$$ |
while read i
do
sotu=`echo $i | wc -w`
ten=`echo $i | cut -d : -f1`
holot=`echo $i | cut -d : -f2`
misc=`echo $i |cut -d : -f3-$sotu`
echo “$holot $ten $misc”|tr -s ‘\t’ ‘ ‘>> ketquadiem
done
cat ketquadiem
#cat /tmp/sortfile.$$
fi

./baicuoi1 tendanhsach (chay file bai cuoi)

file danh sach
Nguyen Thi Kim : Phuong : TH0003 : 5
Tran Ngoc : Phuc : Th006 : 10
Nguyen Nhat : Quang : TH001 : 8
Nguyen Cong : Tam : TH0010 : 4
Phan Duc : Anh : TH0010 : 7

##################################
#baicuoi2
if [ $# -ne 2 ]
then
echo “Error..Give me one name to find mark and give mark list”
exit 1
else
grep -i $1 $2
fi
#####################################
./baicuoi2 tencantim danhsachcantim
ex: ./baicuoi2 billyduc ketqua.txt

Bravo ^^ Have anyquestion ?? Send it to me ^^

rpm and yum rescue tips on Fedora

You have to be careful when you run yum update and yum install, DON’T force kill it, kill -9 or pkill -9. Those action are consider very dangerous, may lead you to losing certain files. Seriously, I hate yum, when I really wanna cancel the process in the middle, by hitting ctrl+c doesn’t really work! So, I do pkill -9, and I bare the consequences!

Some binaries are missing although the rpm query indicates those packages are successfully installed; some icons are missing, and I have no idea what’s wrong, I almost lose hope to reinstall everything. Thanks to my comrades Kagesenshi guiding me through finding the cause and I eventually fix it. Now, I share what I have done during the rescue.

First, let us look at how you can know better of what was installed in your system. With rpm query command lines, you can find out a lots of information.

Query All:

rpm -qa

This is what people usually do, combines with grep you can check whether a particular package is it install into your system.:

rpm -qa | grep mplayer

It takes sometimes if your system installed with tons of packages, you can also ignores the ‘a’ if you know the package name:

rpm -q mplayer

What files the particular package contains:
This is very important, sometimes the binary do not appear as the same as package name, for example: vim. And sometimes the package contains more than one binary.

rpm -qs vim-enhanced-7.1.245-1.fc8

normal        /etc/profile.d/vim.csh
normal        /etc/profile.d/vim.sh
normal        /usr/bin/ex
normal        /usr/bin/rvim
normal        /usr/bin/vim
normal        /usr/bin/vimdiff
normal        /usr/bin/vimtutor
normal        /usr/share/man/man1/rvim.1.gz
normal        /usr/share/man/man1/vimdiff.1.gz
normal        /usr/share/man/man1/vimtutor.1.gz

This binary is from which package?
This is also important, as sometimes I know the binary name but I do not know what package it bundle with, for example: ifconfig. To check for this, I need to specified absolute path of the binary, therefore i use which.

rpm -qf `which ifconfig`
net-tools-1.60-84.fc8

Ok, now lets look at one of the yum utils command, package-cleanup.
package-cleanup allows you to detects package duplication, performs clean up and also checks on the missing dependency packages etc.

Any dependency problems?

package-cleanup --problems

Any duplication packages?

package-cleanup -d

Clean up those duplicated packages.

package-cleanup --cleandupes

If yum crashed, or interrupted halfway, you may try this to resume those yum transaction.

yum-complete-transaction

Sometimes, when rpm returns the result state that you have installed certain packages, some binaries might be missing if yum is been interrupted during installation process. For my case, my nm-applet binary was missing, nm-applet is bundle in NetworkManager-gnome package, but rpm query indicates my system was installed with NetworkManager-gnome.

Therefore, goes back to rpm, I verify all the packages to ensure all binaries from those packages was still there.

rpm -Va > rpmva.txt

Store that into a file, I will need that info to rescue my system. Here is a portion of the output:

...
missing   /usr/share/devhelp/images
missing   /usr/share/devhelp/images/book_closed.png
missing   /usr/share/devhelp/images/book_open.png
missing   /usr/share/devhelp/images/helpdoc.png
missing   /usr/share/devhelp/ui
missing   /usr/share/devhelp/ui/window.ui
S.5....T c /etc/passwd
...

You only want to focus on packages that its binaries are missing, therefore, perform awk to filter it.

awk ' $1 ~ /^missing$/ {print $2}' rpmva.txt > rpm-filemissing.txt

With missing file information, you can obtain package’s name by rpm -qf. The same package ’s name may appear multiple times, you can use uniq to filter it.

rpm -qf `cat rpm-filemissing.txt` | uniq > pkg-reinstall.txt 

WARNING! Make sure you have internet access! check the package list, removes yum from the list or you can download yum rpm from the internet first, you are going to perform rpm removes on next step, after that yum the packages from the internet.

1. Removes problem’s rpm!

rpm -e --nodeps `cat pkg-reinstall.txt`

2. Clean all rpm cache downloaded by yum (optional)

yum clean all

3. Reinstall those packages!

yum -y install `cat pkg-reinstall.txt`

4. Check again to make sure all solves!

rpm -Va; package-cleanup --problem

From: Linuxbyexample

Installing true type fonts for linux

While searching the ways of installing true type fonts to linux, I get all sort of solutions. Some will ask you to copy and paste to fonts:/// folders in nautilus, or fonts:/ in konqueror. Some may even ask you to copy your ttf fonts to /usr/share/fonts and run fc-cache. All sort of ways doesn’t works so well during last two years.

Nowadays, I think all sort of ways may works under particular linux distro, the steps to install font might vary between different linux distros, but its they a common way that it will works for any distro? For me, installing custom fonts should be as straight forward as ‘copy and paste’ ttf files to a specific folders without needing to run any command or configuration script.

Recently, I find the ‘copy and paste’ way. I just need to copy my downloaded ttf font files to ~/.fonts. If your home directory does not contain .fonts folder, create a new one

For examples, I download a font from a site, it consist of multiple ttf files.

Readme.txt
SF New Republic Bold Italic.ttf
SF New Republic Bold.ttf
SF New Republic Italic.ttf
SF New Republic Sample.jpg
SF New Republic SC Bold Italic.ttf
SF New Republic SC Bold.ttf
SF New Republic SC Italic.ttf
SF New Republic SC.ttf
SF New Republic.ttf

I create a new folder “SF New Republic” in ~/.fonts , and copy all these files into that folder. Next I open oowriter ( open office writer), straight away I can use the font without doing fc-cache or any configurations.

Anyway, there is a command to verify fonts have successfully installed to your system:

fc-list | grep "SF"
SF New Republic:style=Regular
SF New Republic:style=Bold
SF New Republic:style=Bold Italic
SF New Republic SC:style=Bold
SF New Republic SC:style=Italic
SF New Republic SC:style=Regular
SF New Republic SC:style=Bold Italic
SF New Republic:style=Italic

fc-list is actually listing all the installed fonts, with pipe over grep, we can verified whether are those fonts successfully installed.

I have tested this method on:
1. Ubuntu Hardy Heron 8.04
2. Fedora 8

I would like to do a survey at here, if you are running different distro listed above, can you try out this method?

p.s. You can download fonts at http://www.dafont.com

From : linuxbyexample

10 Linux shell tricks you don’t already know. Really, we swear.

Shell

Yeah, I’ve read them too. Lists of shell tricks you already know - pstree (wow!) bc (bash already has built-in math), and a dozen commands you see in every Linux site, book, and training course.

Here’s a list of damn useful commands you haven’t heard before.

1. A Simple way to Send Output and Errors
Want to send output and errors to the same file?

command &> file

Maybe you’re troubleshooting a problematic app with strace, and want to see the system calls at the same time as the apps errors?

strace badapp &> errors_and_output

Benefit: Easy to remember, and simpler than ’send errors to output, and then send that to a file’
Works in: any currently supported Linux

2. Parallelize Your Loops
Almost every Linux network administrator knows the power of the for loop: the way to do something for one, one hundred or one thousand users, files, machines, processes, or whatever else. Most people set their loops in sequence – so that each jobs is finished before moving onto the next.
But the jobs command can be used to background each loop, so you don’t have to wait for it to complete before continuing with the next.

Here’s an example running an apt-get update:

for HOST in $(< ListOfHosts); do ssh $HOST ’sudo apt-get update’ & done

Maybe you need a bunch of SSH tunnels running simultaneously:

for HOST in $(< ListOfHosts); do ssh -C -N -R 80:localhost:80 $HOST & done

Sometimes you probably don’t want to see all the output as it happens – in that case, save a file on each machine and use another loop to collect it later.

Benefit: Saving a metric shitload (2/3rd of an imperial shitload) of time waiting on stuff to finish
Works in: any currently supported Linux
Drawbacks: Bash probably has some limits of the amount of concurrent jobs. But I’ve yet to run into them.

3. Catch Memory Leaks By Using Top via Cron
Memory apps are rare in Linux, but they do happen, particularly when using beta distros or home grown software. A lot of time the identitty of the app with a memory leak isn’t that apparent. Linux has an Out-Of-Memory app built in to identify and kill these apps, but by the time it eventually kicks on your system may have been unusually slow for a while – and that’s if your patience hasn’t already worn thin and you’ve rebooted.

The normal way to find an apps memory consumption is by running top (or one of it’s graphical equivalents, like System Monitor) and check the Resident Set Size (called Res or RSS) of the processes you care about (you can ignore figures for how much memory the app has allocated – memory leaks come from usage, not allocation, and apps can assign bucketloads of memory they don’t use without hurting your system). Most people aren’t aware top can be run non-interactively, which means you can use cron and top to generate a simple report of an apps usage over time.

  • Run top.
  • Use the < and > keys until processes are sorted by RES (resident memory usage).
  • Hit W to write your config out to a file
  • Add a cron job:

    crontab - <<< ‘*/15 * * * * top -n 1 -b’

You’ll now get an email every 15 minutes with the top output.

Benefit: way less complicated than adding software like SAR
Works in: any currently supported Linux
Drawbacks: Has some limitations of the amount of concurrent jobs.

4. Standard in directly from the command line

Wondering what the hell the <<< above was? Bash allows you to send programs stdin directly from the command line.

Benefit: Let’s you write your command on the goddamned commandline, even for weird creepy programs that want you to do everything via standard in. Shakes fist at MySQL.
Works in: Bash 3 and newer.
Drawbacks: Still quite a few Bash 2.x systems out there.

5. Set a Random Initial Password, That Must be Changed
There’s a lot of organizations who have nice, secure policies for passwords. Passwords stored on Windows machines. Linux is either not covered by the policy or the policy is routinely violated – people have idea about Linux authentication (most people don’t quite understand PAM, and Linux admins don’t often realize Linux can quite happily authenticate to Active Directory) and once upon a time, the OpenSSH developers didn’t like PAM (that’s since changed).

To set password that must be changed upon first login.

umask u=rw,go=
openssl rand -base64 6 | tee -a PasswordFile | passwd –stdin joe
chage -d 0 joe

The password is saved to PasswordFile , which only your own account can read. Then contact via some medium you consider relatively secure – like a phone call or encrypted email and them tell their initial password.

Benefit: Ensures users aren’t using your default password forever
Works in: any currently supported Linux where OpenSSH has been updated (if your users use SSH to do their first login). Red Hat still say this doesn’t work in the RHEL 3 / 4 documentation, but with their own updates applied, it’s AOK.
Drawbacks: None

6. Add Your Public Key to Remote Machines the Easy Way
In order to perform key based logins to a new machine, you need to get a copy of a public key to the remote machine yourself. Sure, you could do this manually – which gets a bit boring after a while (why doesn’t SSH have an authorized_keys.d anyway?), but why waste time when SSH comes with it the tool to do it?
Just run:

ssh-copy-id -i .ssh/id_rsa.pub hostname

After being prompted to enter your password for the last time, SSH will say:
Now try logging into the machine, with “ssh ‘hostname’”, and check in:

.ssh/authorized_keys

to make sure we haven’t added extra keys that you weren’t expecting.

Try it. No more passwords!

7. Extract an RPM without any additional software
This one isn’t necessary on Debian based distros, as .deb are merely ar archives. Every Red Hat guide ever written mentions using rpm2cpio (which comes as part of the default rpm package), but frankly I can never be bothered remembering the weird syntax to cpio, the ancient archive format used by …uh, pretty much just rpm.

The following command installs a package to a temporary directory, and but doesn’t modify your RPM database (just one in the temporary directory, whose contents you can delete afterward). Since the temp directory doesn’t have any othr software in it, we also disable dependencies and scripts.

mkdir /tmp/deleteme

rpm -ivh –root /tmp/deleteme –nodeps –noscripts package.rpm

8. See How a File Has Changed from Factory Defaults
This is a simple troubleshooting tool when you’re not sure how a file has changed from its defaults. First identify the package that owns the file:

dpkg -S /etc/foo/foo.conf

rpm -qf /etc/foo/foo.conf

Then extract the original package either with tar (DPkg) or the rpm trick above (RPM) and run:

diff /etc/foo/foo.conf /tmp/deleteme/etc/foo/foo.conf

And see the differences.
Benefit: Faster troubleshooting of bad config files (note strace is also handy in these cases)
Works in: any currently supported Linux
Drawbacks: You have more time free at work, to spend reading Digg.

9. Undo Your Network Screwups After You’ve Lost the Connection
Messing with a firewall or a network over a remote connection? Nerve wracking isn’t it? Change the wrong setting and you’ll be locked out, unable to fix it.

So why not undo your mistake? Schedule a job to run at a later time that undoes what you’re about to do.

at now + 5 minutes <<< ‘cp /etc/ssh/sshd_config.old /etc/ssh/sshd_config; service sshd restart’

If you screw up, the job will run and restore things to the way they were.

If you your change works, then just run atq to check the queue of upcoming at jobs, and atrm jobNumber to remove it.

Benefit: Gets you back in after you lock yourself out.
Works in: any Linux provided atd is enabled - which is usually the case.
Drawbacks: Remembering to do it before you make the risk change.

10. Check a Port is Open

Want to check whether a network service is running before you use it? Netcat can be used to easily connect to ports, and has a rather handy wait -w option to tell it how long to wait for.

nc -w 3 server ssh <<< ‘ ‘

Would connect to the ssh port on a machine called server, and wait for up to 3 seconds before sending it, er, nothing, and closing the connection. Whether the port was open will be reflected by nc exit status.

if nc -w 3 localhost 22 <<< ” &> /dev/null
then
echo ‘Port is open’
else
echo ‘Port is closed’
fi

Here’s a few bonus tricks, which you may already know…

Bonus Trick 1: The Easy Way to Extract Tar Archives

New to Linux? Don’t feel like using File Roller to extract archives? Despite everything you rad on the internet, tar (the tape archiver - that why you have to tell it you want to use a file with -f) doesn’t need you to specify archive file formats any more. To extract a file, simply:

tar -xf archive.tgz

But keep reading…

Benefits: No stupid messages from a computer asking for information the computer can determine on its own.
Works in: Recent distros (last year) only
Drawbacks: It’s still to early to use this in a lot of distros.

Bonus Trick 2: Use Math Shells

Most of you already know this, but since digg.com keeps linking to articles about ‘bc’, it’s worth pointing out that Bash comes with it’s own math shells. These can be invoked like an ordinary subshell, but by using two round brackets. Say you have a n script that needs to figure out disk space.

SIZE_IN_KB=204535848
SIZE_IN_GB=$(( $SIZE_IN_KB / 1024 / 1024 ))
echo $SIZE_IN_GB

Benefit: No need for an extra process like bc every time you need to work with number
Works in: any currently supported Linux.
Drawbacks: If you want to do floating point or other advanced math, you’ll probably want to bust out python.

Bonus Trick 3: Never reboot a system for NFS failures

OK, this isn’t a shell trick. It’s more of a general thing for NFS that not enough people know. We’ve included it here because VentureCake loves you.

At some point every Linux admin has had a problem with a computer using a hard-mounted NFS export, where the connecton to the server has been lost - perhaps the network had a problem or the server went down. Any processes which check the status of filesystems - df, rpm, etc. - will hang, waiting on the storage to respond. Next time, you’ll want to mount using the intr option (not soft - see the Linux NFS FAQ). This time, run:

killall -KILL rpciod

rpciod (the kernel process that handles NFS IO), will instantly respawn, sending errors to processes waiting for NFS IO, causing them to respond. If you’re mounting exports from multiple NFS servers and only wish to time out a single connection, you can do so with:

iptables -A OUTPUT -d nfsserver -j REJECT

Within about a minute, the NFS client will decide the server is unreachable. Again, the processes start responding.

You can now unmount the NFS server. No need to reboot.

Benefit: No need to reboot when an NFS mount fails.
Works in: any Linux.
Drawbacks: You can’t disable an individual NFS export, just all the exports from A particular NFS server. Still beats rebooting though.

Bonus Trick 4: Encourage Others to Use & Contribute to Your Scripts

If you want to improve your scripting skills, it pays to be kind to your peers.

  • Use self-explanatory uppercase names for your variables. In particular, this means not using ‘i’ as a variable name, so when your fellow scripter is eighty lines down your twelfth, nested, for loop, they don’t have to scroll up and work out what the hell ‘i’ means now, when it’s much easier to come to your house and kill you with an axe.
  • Keep your loops and conditionals indented
  • Putting your functions at the top of the script, and check input.

Bonus Trick 5: Shell Sites That Don’t Suck

There’s a lot of sites on Linux shell commands. Very few are Bash specific, so you’ll be missing out on a lot of the good stuff. They also tend to be non-task oriented - if they need to show you grep, they’ll show it using some weird thing about animals, rather than, say how to strip comments and blank lines from a file.

grep -vE ‘^$|^#’ /etc/foo.conf

…by the way. Anyway, here’s a few of our personal favorites:

Tips from an RHCE - Part of Red Hat Magazine, but useful even if you’re not into Red Hat.
SHELLdorado - Not Linux specific, and a little out of date, but very practically oriented- lots of sample scripts you can pillage and plunder.
Handy Sed One Liners - Another ancient document, but the examples covered in it show 99% of what you want to use sed for.

Enjoy this article? Next week I’ll be showing you how to make OpenOffice documents from the shell. If you’re here from digg you’ll probably also want to read The 100.

From : http://www.venturecake.com