Scripts: variables and arguments
The shebang line and the execute permission, assignment without spaces, single and double quotes, command substitution and integer arithmetic, read, and the parameters $0, $1, $#, $@: reading a Bash script and predicting what it prints.
- 26 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Shell variable: what is it?
Show the answer
A name the shell binds to a piece of text, set with
name=valuewith no space around the=and read back with$name.Without the
$, the shell does not read the variable:echo nameprints the wordname, whereasecho $nameprints its value.The script
s.shbelow is launched with./s.sh a "b c" d. What does it print?
```bash
#!/bin/bash
echo $#
echo "$2"`3thenb c4thenb c3thenb4thenb
Show the answer
3thenb cThe quotes around
b cmake it a single argument: there are therefore three, and the second isb c.To launch a script with
./s.sh, the file needs the execute permission, set with …; its … line, at the top, names the interpreter that will run it.Show the answer
To launch a script with
./s.sh, the file needs the execute permission, set with chmod +x; its shebang line, at the top, names the interpreter that will run it.Without the execute permission, direct launching fails (
Permission denied);bash s.shstill works, because the file is then merely read. A shebang pointing to a path that does not exist givesbad interpreter.Positional parameter: what is it?
Show the answer
A value received on a script's launch line and designated by its rank:
$1for the first,$2for the second, and so on.$0is the script's own name,$#the number of values received,"$@"the list of all of them, each staying a single word.A script written on Windows, launched with
./s.sh, answersbash: ./s.sh: /bin/bash^M: bad interpreter: No such file or directory, although/bin/bashexists. Which fix is needed?- Give the script the execute permission with
chmod +x s.sh - Replace the first line with
#!/bin/sh, which is more portable - Install Bash, which is missing from the
/bin/bashlocation - Convert its Windows line endings to Unix line endings, with
dos2unix
Show the answer
Convert its Windows line endings to Unix line endings, with
dos2unixThe
^Mis the carriage return Windows puts at the end of each line: the system looks for an interpreter namedbashfollowed by that character, which does not exist. Without thexpermission, the message would bePermission denied, and another shebang would keep the same^M.- Give the script the execute permission with