Linux bash loop on user input
Linux bash loop on user input
When you need a bash function that iterates over a space-separated list of inputs, this is the pattern. The for input in ${1} loop splits on spaces automatically. Combined with the "$@" trick for calling named functions, this gives you a lightweight way to batch-process command line arguments.
- Create an empty file with .sh extension
1
$ touch test.sh
- Use your favourite editor add a method to the file
1
2
3
4
5
6
7
8
9
10
11
$ vi test.sh
#!/bin/bash
function loop_on_user_input(){
for input in ${1} ; do
echo "Your input is $input"
done
}
"$@"
”$@” is what that makes the script file (.sh) be able to call methods
- Make file executable
1
$ chmod u+x test.sh
- Call method with space separated multiple inputs
1
2
3
4
5
$ ./test.sh loop_on_user_input 'A B C D'
Your input is A
Your input is B
Your input is C
Your input is D
This post is licensed under
CC BY 4.0
by the author.