# How to effectively use bash scripting (different cost reductive ways and good habits)? [closed]

-

## closed as not constructive by jw013, rush, Mat, warl0ck, Michael Mrozek♦Oct 15 '12 at 14:20

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

Avoid the Advanced Bash Scripting guide on TLDP - by the time you know enough scripting to tell the bad practices apart from the good, you won't need it anymore. Instead use the Wooledge Wiki for bash. For portable POSIX shell, use the POSIX spec. –  jw013 Oct 15 '12 at 13:34
@jw013: Thanks a lot mate, it looks very useful .Upvoted . –  The Dark Knight Oct 15 '12 at 13:50
any other answers/comments ? –  The Dark Knight Oct 15 '12 at 15:15

1.There is no need to define directory trees individually :

~ $mkdir tmp ~$ cd tmp
~/tmp $mkdir a ~/tmp$ cd a
~/tmp/a $mkdir b ~/tmp/a$ cd b
~/tmp/a/b/ $mkdir c ~/tmp/a/b/$ cd c
~/tmp/a/b/c $ Good Way : ~$ mkdir -p tmp/a/b/c


2. Archiving :

Sometimes i have seen people move any tar like a.tar to another directory which happens to be the directory where they want to extract the archive. But that's not needed , as the -C option can be used here to specify the directory for this purpose.

~ $tar xvf -C tmp/a/b/c newarc.tar.gz  3. Importance of control operators : Suppose there are two commands, but only if the first command runs , then the second one must run, otherwise the second command would have run for nothing . So , here a command must be run, only if the other command returns a zero exit status. Example : ~$ cd tmp/a/b/c && tar xvf ~/archive.tar


In the above example, the contents of the archive need to be extracted in the directory : c, but only if the directory exists.If the directory does not exist, the tar command does not run, so nothing is extracted.

-
@ALL: Kindly share your knowledge guys. It will be very helpful for me. Thanks. –  The Dark Knight Oct 15 '12 at 13:20
Of course, it is an asset to know the options etc. of commands, and it is always good to reason (think, write) about your tools (as a way to learn), but I wouldn't call your guidelines examples of good vs. bad habits. In your examples, it won't really matter what you do, as long as you do it right. Compact code may be "cool" and faster to type but it won't matter that much. Rather, an example of a bad habit is - you have a loop, and the iteration condition is (i < c(a)), and c(a) is always the same. In that case, you should store b = c(a) before the loop and use the condition (i < b). –  Emanuel Berg Oct 15 '12 at 20:32