Questions about shell scripts, executable files that are interpreted by a shell (bash, zsh, etc.).

learn more… | top users | synonyms (1)

137
votes
10answers
12k views

In Bash, when to alias, when to script, and when to write a function?

It's taken me almost 10 years of Linux usage to ask this question. It was all trial and error and random late-night internet surfing. But people shouldn't need 10 years for this. If I were just ...
55
votes
5answers
8k views

Why is it better to use “#!/usr/bin/env NAME” instead of “#!/path/to/NAME” as my shebang?

I notice that some scripts which I have acquired from others have the shebang #!/path/to/NAME while others (using the same tool, NAME) have the shebang #!/usr/bin/env NAME. Both seem to work ...
34
votes
2answers
2k views

$VAR vs ${VAR} and to quote or not to quote

I can write VAR=$VAR1 VAR=${VAR1} VAR="$VAR1" VAR="${VAR1}" the end result to me all seems about the same. Why should I write one or the other? are any of these not portable/POSIX?
31
votes
3answers
7k views

Multiline shell script comments - how does this work?

Recently, I stumbled upon a multiline comment type I have never seen before - here is a script example: echo a # : aaa : ddd # echo b This seems to work, hell, even vim syntax-highlights it. What ...
27
votes
5answers
2k views

Better way of accepting variations of ‘Yes’ from a shell prompt

Usability testing of a shell script I wrote found that people had different expectations on how to answer a question that expected ‘yes’ as the answer. See variations in the below code example. ...
26
votes
9answers
11k views

Correct locking in shell scripts?

Sometimes you have to make sure that only one instance of a shell script is running at the same time. For example a cron job which is executed via crond that does not provide locking on its own (e.g. ...
23
votes
9answers
860 views

for vs find in Bash

When looping through files there are two ways: 1. use a for-loop for f in *; do echo "$f" done 2. use find find * -prune | while read f; do echo "$f" done Assuming these two loops will ...
21
votes
7answers
813 views

Should scripts that require sudo fail if they don't have it, or use sudo and prompt?

I have a script which gives me fine-grained control over my backlight brightness and requires sudo to run. It's essentially this: backlight="/sys/class/backlight/acpi_video0/brightness" echo $1 | tee ...
21
votes
3answers
3k views

How to do nothing forever in an elegant way?

I have a program which produces useful information on stdout but also reads from stdin. I want to redirect its standard output to a file without providing anything on standard input. So far, so good: ...
21
votes
2answers
715 views

Should I care about unnecessary cats?

A lot of command-line utilities can take their input either from a pipe or as a filename argument. For long shell scripts, I find starting the chain off with a cat makes it more readable, especially ...
20
votes
6answers
6k views

Can a script be executable but not readable?

Is it possible to execute a script if there is no permission to read it? In root mode, I made a script and I want the other user to execute this script but not read it. I did chmod to forbid read and ...
20
votes
3answers
3k views

What's the standard for indentation in shell scripts?

Java community use 4 spaces as the unit of indentation. 1 Ruby community use 2 spaces that is generally agreed-upon. 2 What's the standard for indentation in shell scripts? 2 or 4 spaces or 1 tab?
20
votes
2answers
720 views

Why escape trivial characters in shell script?

I just opened a legacy shell script (written in old ksh88 on Solaris) and found the following repeated all throughout the code: [ -f $myfile ] && \rm -f $myfile The escaping backslash ...
19
votes
8answers
12k views

Different ways to execute a shell script

There a several ways to execute a script, the ones I know are: /path/to/script # using the path (absolute or relative) . script # using the . (dot) source script # using the `source` command ...
18
votes
5answers
12k views

Split pages in pdf

I have a scanned pdf file which has scanned two pages on one virtual page (page in pdf file). The resolution is with good quality. The problem is I have to zoom when reading and drag from left to the ...
18
votes
3answers
741 views

Which are the standard commands available in every Linux based distribution?

I would like to know which are the standard commands available in every Linux system. For example if you get a debian/ubuntu/redhat/suse/arch/slackware etc, you will always find there commands like: ...
17
votes
7answers
2k views

What purpose does the colon builtin serve?

I've hacked on a lot of shell scripts, and sometimes the simplest things baffle me. Today I ran across a script that made extensive use of the : (colon) bash builtin. The documenation seems simple ...
17
votes
3answers
5k views

How do I exit a script in a conditional statement?

I'm writing a bash script where I want to exit if the user is not root. The conditional works fine, but the script does not exit. [[ `id -u` == 0 ]] || (echo "Must be root to run script"; exit) ...
17
votes
2answers
2k views

aliasing cd to pushd - is it a good idea?

Is it a good idea to use the following alias: cd() { pushd $1; } in bash? I think this would be very useful, since I can then use a series of popds instead of just a cd - once. Is there any ...
17
votes
1answer
447 views

Is there a standard command that always exits with a failure?

I want to test my script with a command that fails. I could use an existing command with bad arguments. I could also write a simple script that immediately exits with a failure. Both of these are easy ...
17
votes
1answer
2k views

Execute bash scripts on entering a directory

What is the best way to execute a script when entering into a directory? When I move into a new directory I would like bash to execute the projectSettings.bash script much like RVM does.
16
votes
2answers
280 views

Shell function definition: why is there a space after the opening brace?

You probably know of that fork bomb: :(){ :|:&};: #WARNING: harmful code I wonder why it is necessary, for it to parse, to include a space after the opening curly brace.
15
votes
3answers
663 views

What is the difference between [[ $a == z* ]] and [ $a == z* ]?

Is there is any difference between these two. [[ $a == z* ]] and [ $a == z* ] Can I have an example where they would have different outputs? Furthermore, how does the working of [[ ]] differs ...
15
votes
3answers
4k views

What does it mean to have a $“dollarsign-prefixed string” in a script?

I just saw this in an init script: echo $"Stopping Apache" What is that dollar-sign for? My research so far: I found this in the bash manual: extquote If set, $'string' and ...
15
votes
3answers
28k views

What characters do I need to escape when using sed in a sh script?

Take the following script: #!/bin/sh sed 's/(127\.0\.1\.1)\s/\1/' [some file] If I try to run this in sh (dash here), it'll fail because of the parentheses, which need to be escaped. But I don't ...
14
votes
8answers
2k views

What is the utility of the : command in shell scripting, given that it explicitly does nothing?

In the answer to this question about comments in shell scripting, it is indicated that the : is a null command that explicitly does nothing (but is not to be used for comments). What would be the ...
14
votes
3answers
1k views

If I sudo execute a Bash script file, will all commands inside the Bash script be executed as sudo as well?

I want to write an automated post-installation script in Bash (called post-install.sh, for instance). The script will automatically add and update repositories, install and update packages, edit ...
14
votes
4answers
5k views

How can I detect if the shell is controlled from SSH?

I want to detect from a shell script (more specifically .zshrc) if it is controlled through SSH. I tried the HOST variable but it's always the name of the computer which is running the shell. Can I ...
14
votes
3answers
602 views

Newlines in filenames

I understand and accept the premise that defensive1 shell scripting is both prudent and, in the longer term, more sustainable. Many of the answers to text processing questions here follow this ...
14
votes
2answers
1k views

In bash, is it possible to use an integer variable in the loop control of a for loop?

I have the following bash script: #!/bin/bash upperlim=10 for i in {0..10} do echo $i done for i in {0..$upperlim} do echo $i done The first for loop (without the variable upperlim in the loop ...
14
votes
4answers
12k views

How to introduce timeout for shell scripting?

I want to run a shell script that got a loop in it and it can go for ever which I do not want to happen. So I need to introduce a timeout for the whole script. How can I introduce a timeout for the ...
14
votes
2answers
2k views

How can I test for POSIX compliance for shell scripts?

Probably the main thing that this website has taught me so far is the importance of writing portable shell scripts. Considering that POSIX is the closest thing to a common standard between all ...
13
votes
4answers
5k views

What is the meaning of $? in a shell script?

When going through one shell script, I saw the term "$?". What is the significance of this term?
13
votes
6answers
8k views

How to get my own IP address and save it to a variable in a shell script?

How can I get my own IP address and save it to a variable in a shell script?
13
votes
1answer
1k views

Can bash case statements cascade?

I'm trying to do something like this: case $level in 3) echo "Level Three" 2) echo "Level Two" 1) echo "Level one" ;; esac where if $level = 3, it ...
13
votes
3answers
3k views

How can one run multiple programs in the background with single command?

How can one run multiple programs in the background with single command? I have tried the commands below, but they do not work. nohup ./script1.sh & && nohup ./script2.sh & -bash: ...
13
votes
2answers
7k views

Execute a command before shutdown

I want to execute a simple command just before the computer shuts down (timing is not essential). For startup I can use /etc/rc.local - is there something similar for shutdown? Note that I would ...
13
votes
3answers
2k views

How to properly collect an array of lines in zsh

I thought the following would group the output of my_command in an array of lines: IFS='\n' array_of_lines=$(my_command); so that $array_of_lines[1] would refer to the first line in the output of ...
13
votes
3answers
11k views

Testing if a variable is empty in a shell script

I have seen the following technique used many times on many different shells, to test if a variable is empty: if [ "x$1" = "x" ]; then # Variable is empty fi Are there any advantages on using ...
13
votes
3answers
425 views

When does `ls -s` print “0”

Of course, the standard way of testing if a file is empty is with test -s FILE, but one of our clients have received a script containing tests like this: RETVAL=`ls -s ./log/cr_trig.log | awk '{print ...
13
votes
4answers
2k views

How to make bash abort the execution of a script on syntax error?

To be on safe side, I'd like bash abort the execution of a script if it encounters a syntax error. To my surprise, I can't achieve this. (set -e is not enough.) Example: #!/bin/bash # Do exit on ...
13
votes
2answers
2k views

Rule for invoking subshell in Bash?

I seem to misunderstand the Bash rule for creating a subshell. I thought parentheses always creates a subshell, which runs as its own process. However, this doesn't seem to be the case. In Code ...
13
votes
4answers
743 views

keep duplicates out of $PATH on source

I have the following code that's source-d by my .shellrc PATH="${PATH}:${HOME}/perl5/bin" PATH="${PATH}:${HOME}/.bin" export PATH but if I make changes to other code and then source this file, my ...
12
votes
2answers
588 views

When to use a semi-colon between environment variables and a command

Can anyone explain why the semi-colon is necessary in order for the LANG to be seen as updated by bash? Doesn't work: > LANG=Ja_JP bash -c "echo $LANG" en_US Works: > LANG=Ja_JP ; bash -c ...
12
votes
2answers
337 views

Should I use $* or $@?

Which one of $* or $@ is better to use (in array syntax,command line parameters, etc.) to avoid any bugs/problems in code? Or it does not make any difference?
12
votes
5answers
342 views

Stateful bash function

I’d like to implement a function in Bash which increases (and returns) a count with every call. Unfortunately this seems non-trivial since I’m invoking the function inside a subshell and it ...
12
votes
3answers
293 views

When to use redirection to stderr in shell scripts

I know that well-behaved utilities like grep output "normal" messages to stdout, and error messages to stderr. $ grep '^foo' file1 file2 file1:foo grep: file2: No such file or directory When I'm ...
11
votes
4answers
1k views

How Does Linux deal with shell scripts?

For this question, let's consider a bash shell script, though this question must be applicable to all types of shell script. When someone executes a shell script, does Linux load all the script at ...
11
votes
3answers
9k views

Find the owner of a directory or file, but only return that and nothing else

I am looking for a command that will return the owner of a directory and only that--such as a regex parsing the ls -lat command or something similar? I want to use the result in another script.
11
votes
5answers
8k views

How to compare to floating point number in a shell script

I want to compare two floating point numbers in a shell script. The following code is not working: #!/bin/bash min=12.45 val=10.35 if (( $val < $min )) ; then min=$val fi echo $min