How to split input string into multiple variable

2019-08-27 19:23发布

I'm working on shell script and trying to split user input into multiple variable and use them at different places.

User input is not fixed so can't really assign fixed number of variable, input is separated by comma ,

./user_input.ksh -string /m01,/m02,/m03

#!/bin/ksh
STR=$2

function showMounts {
    echo "$STR"

    arr=($(tr ',' ' ' <<< "$STR"))
    printf "%s\n" "$(arr[@]}"

   for x in "$(arr[@]}"
     do
       free_space=`df -h "$x" | grep -v "Avail" | awk '{print $4}'`
       echo "$x": free_space "$free_space"
    done

#total_free_space = <total of $free_space>
#echo "$total_free_space"
}

Basically $STR* variable value is filesystem mount points

Host output if run separate df -h command

$ df -h /m01 | grep -v "Avail" | awk '{print $4}'

***Output***
 150

Current problems:

(working)1. How to get free space available for each /m* using df -h?

4条回答
淡お忘
2楼-- · 2019-08-27 19:49

A variation on the theme:

# cat user_input.ksh

#!/bin/ksh
c=1
for i in $(echo ${@} | tr "," " ")
do
    eval STR$c="$i"
    ((c=c+1))
done

printf "\$STR1 = %s; \$STR2 = %s; \$STR3 = %s; ...\n" "$STR1" "$STR2" "$STR3"

Which gives you:

# ksh ./user_input.ksh /m01,/m02,/m03,/m04
$STR1 = /m01; $STR2 = /m02; $STR3 = /m03; ...

Hope that helps..

--ab1

查看更多
走好不送
3楼-- · 2019-08-27 19:51

Easiest thing to do is to use shell array here like this:

#!/bin/ksh
str='/m01,/m02,/m03'

arr=($(tr ',' ' ' <<< "$str"))
printf "%s\n" "${arr[@]}"

Output:

/m01
/m02
/m03

To read elements individually you can use:

"${arr[0]}"
"${arr[1]}"
...

Update: Here is your corrected script:

#!/bin/ksh
STR="$2"

arr=($(tr ',' ' ' <<< "$STR"))
printf "<%s>\n" "${arr[@]}"

for x in "${arr[@]}"; do
   echo "$x"
   free_space=`df -h "$x" | awk '!/Avail/{print $4}'`
   echo "$free_space"
done
查看更多
走好不送
4楼-- · 2019-08-27 20:03
$ cat tst.sh
str='/m01,/m02,/m03'
IFS=,
set -- $str
for i
do
    echo "$i"
done

$ ./tst.sh
/m01
/m02
/m03

Don't use all-upper-case for variable names unless you are going to export them (by convention and to avoid clashes with built in names like HOME, PATH, IFS, etc.).

For your overall script, you should simply be doing something like this:

df -h "${str//,/ }" | awk '/^ /{print $5, $3; sum+=$3} END{print sum}'

depending on what your df -h output looks like and what you're final output is supposed to be.

查看更多
在下西门庆
5楼-- · 2019-08-27 20:09

you can try,

#!/bin/ksh
STR=/m01,/m02,/m03
read STR1 STR2 STR3 <<<`echo $STR | awk 'BEGIN{FS=","; OFS=" "}{$1=$1; print}'`
echo $STR1 - $STR2 - $STR3

you get:

/m01 - /m02 - /m03
查看更多
登录 后发表回答