I have a script which takes as input a sentence into $1
. How can I split $1
which is for example "abcde"
into a
b
c
d
e
and access them individually ? Using sh
not bash
.
Unlike bash
, sh
does not support arrays. If you need to access each element, you can use the default splitting functionality in say a for
loop:
for w in $1; do
echo $i
done
Output:
a
b
c
Note the lack of quotes around $1
. This ensures that it gets split into words rather than being treated monolithically. Replace echo
with whatever handling your heart desires.
If you are only interested in a specific element, you can use cut
, which will work in any shell since it is a program, not part of sh
:
echo "$1" | cut -d ' ' -f 2
Output:
b
In this case, the quotes around $1
are optional since echo
will dump everything regardless.
A script is named as a.sh
.
#!/bin/bash
tokens=( $1 )
echo ${tokens[*]} # all array data
echo ${#tokens[@]} # length of array
echo ${!tokens[@]} # get all index
echo ${tokens[0]} # first data in array
echo ${tokens[1]} # second data in array
for index in ${!tokens[@]}; do
echo $index : ${tokens[$index]}
done
Run a.sh "abcde"
. You can see the result as following.
$ bash a.sh "a b c d e"
a b c d e
5
0 1 2 3 4
a
b
0 : a
1 : b
2 : c
3 : d
4 : e
Good luck!
You simply need to use double quotes (") to prevent the shell from parsing a, b, and c into separate arguments.
EXAMPLE:
vi cat tmp.sh
#!/bin/sh
echo '$1=' $1 ', $@=' $@
./tmp.sh "a b c"
$1= a b c , $@= a b c
./tmp.sh a b c
$1= a , $@= a b c
NOTES:
The syntax '$1' prevents the shell from "expanding" the first argument, so you see "$" instead of "a"
The abc is treated as 3 arguments ($1, $2 and $3); "abc" is treated as one argument ($1). In this example, "abc" (double quotes) and 'abc' (single quotes) would be equivalent.
The "quote" syntax is the same, regardless if you're using the Bourne shell ("sh") or "bash".
If you wanted to treat an aggregate ("abc") as separate elements, you can use the "$@" argument.
Finally, "/bin/sh" on most systems is the Posix shell, not the Bourne shell. Hence is doesn't necessarily share the Bourne shell's limitations:
a.sh
echo $1 | cut -d ' ' -f $2
run a.sh "abcde" 3
.
c
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.