
- Image via Wikipedia
Lets begin with a link, this is really REALLY REALLY good resource for learning bash (especially the BashFAQ).
Imagine this, you wrote a script for some thing, now that is ready for production you put it in the crontab and let it run from there, BUT in certain conditions that script fails. Assuming the error ain’t trivial the way i tackle the problem is to add something ala this to the top of the script.
exec 2> log.`date +%Y.%m.%d.%H:%M` set -x
The first statement redirects stderr to a certain file, the second statement enables “xtrace” printing commands as they are executed. The undesired side effect of this is that ALL stderr is redirected to that particular file. The alternative to this would be to do proper logging, but if your script is long enaugh that you need proper logging there are pretty good chances that you shouldn’t be doing it in the bash in the first place
.
Ever found yourself wanting to do some simple processing of some command and wanting to use the result?
echo some string | while read; do foo='boo'; done; echo $foo
This echoes nothing as $foo is empty. What happens in the background is that pipes spawn the subshell, so the variable $foo is assigned in the subshell, and when the loop terminates subshell is closed and normal shell is execution is continued, which doesn’t know anything about $foo.
A solution for this is called “process substitution”, to the best of my knowledge it is exactly the same as pipe, only without the subshell part. As a side not, ksh doesn’t spawn subshells with pipes.
while read; do foo='boo'; done < <(echo some string); echo $foo
Let’s talk about dotfiles, specifically about those initializing the shell, in bash that would usually be .bash_profile and .bashrc, what they can be used for is to customize you bash on every startup. The difference is that .bash_profile is executed when a login shell is started (for exmple when you ssh to a box or do “su -”), while the .bashrc is executed when nonlogin shell starts (usually when you start mrxvt/xterm/konsole/…). Why the f**** do we have distinction between the two modes? No good reason really, it’s because we were doing it this way for 20+ years, why break the tradition? :/
[[ $PS1 ]] && exec bash -l
Having the above in .bashrc is the way around this annoyance, it allows you to have all your configuration in .bash_profile. The only thing it does is execute a login shell (thus triggering .bash_profile execution). The condition makes sure that the login shell is executed only when you are in interactive mode (bash by definition/man page set’s PS1 only for interactive shells). A non-interactive shell is spawned when you use scp.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=6ec5af8b-5689-447f-bd10-b8a1bf264eb1)