Scripting Basics Flashcards
Write out the basic structure of a bash script
#!/bin/sh #this points to the intrpreter to use echo "Hello World!" exit 0 #The return value for the script
How do we make a script an executable
chmod +x name-of-script.sh
How do run a script
./name-of-script.sh
What type of file extension does a script need to be saved as
.sh
What is the shell used to run scripts
Bourne
If you want to use a different shell (e.g. zsh, bash), you need to update the script to know to use that environment.
Can you run a script that doesn’t have the opening #!/bin/sh
Yes. You can run it using the sh command.
What’s the comment character for Bourne scripting
#
Declare a shell variable
v1=”Hello World”
What type of value are shell variables
Strings.
Shell scripting does not support other type of variables
How do you use a variable once it’s declared
$variableName e.g. $v1
How do you determine the length of a string
${variableName} e.g. ${#v1}
What does a null value mean in shell scripting
An empty string
Explain the following variable modifier:
v2=${v1:-foo}
If v1 is not empty, use v1; else use the text ‘foo’
Explain the following variable modifier:
v2=${v1:=bar}
If v1 is not empty, use v1; else assign ‘bar’ to v1 and use it
Explain the following variable modifier:
v2=${v1:?}
If v1 is not empty, use v1; else exit with an error message
How would you store the output of a command into a variable?
You would create a vriable and then surround the command in backticks
num=echo $v1 | wc -w
How can you perform arithmatic since shell variables are stored as strings
Use the expr command
v2=3 #3 is stored as a string valueexp
expr $v2 + 1 #returns 4
Or you can use the following shorthand:
v3=$((v3 + 1)) #