LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash script $n variable expansion (https://www.linuxquestions.org/questions/programming-9/bash-script-%24n-variable-expansion-123886/)

cortez 12-08-2003 12:46 PM

bash script $n variable expansion
 
Hello!

I have a problem with this (very simple indeed) script:

if [ -z "$1" ]; then
echo -e "\npsfind v0.3"
echo -e "\tUsage: psfind process1 process2 ...\n"
else
for (( i=0; i<$#; i++ )) do
ps aux | grep -v psfind | grep ${$i} | grep -v grep
done
fi

in the third grep I want the variable $0, $1, etc to be substituted with the argument passed to the script. this way it doesn't work, and ${${i}} doesn't work either.

Any ideas? :confused:

thanks



Luca :D

Tarts 12-08-2003 01:06 PM

You would use:
Code:

"$0" "$1" "$2" ---"${10}" "${11}"
Tarts

cortez 12-08-2003 01:14 PM

Maybe I couldn't explain right what I needed help in, I don't get your point.

The code I showed is not working. I'd like to know how to:

If I do

./myscript foo bar

i'd like

${${i}}

the first time to expand to $1 and then to foo

the second time to expand to $2 and then to bar


thanks

Luca

druuna 12-08-2003 01:31 PM

I'm not able to do the thing you want, but I am able to show you another way (roughly same as your original) that will do what you want:
Code:

#!/bin/bash

ALLINPUT="$@"

if [ ! -z "${ALLINPUT}" ]
then
  for PROCESS in ${ALLINPUT}
  do
    ps -aux | egrep -v 'psfind|grep' | grep ${PROCESS}
  done
else
  echo -e "\npsfind v0.3"
  echo -e "\tUsage: psfind process1 process2 ...\n"
fi

$@ holds all that was given to the script.
The for PROCESS in ${ALLINPUT} will keep working untill all in ${ALLINPUT} is given to the do ..... done loop. So you don't need any counters to check id there are any left.

I also turned around the error part. Why?? this way you have a little speed increase. Most of the times you will give an argument to psfind, so if you check that first you win a few clock sicles ;)

cortez 12-08-2003 01:55 PM

Thanks a lot...
 
That's quite a nice solution, but my mind just asks for the solution of that variable expansion thing... i just need to know how I do that! :mad: :D

just for the form you can also change

if [ ! -z $1 ]

in

if [ -n $1 ]


bye

Luca

druuna 12-08-2003 02:27 PM

Ok, let's do it your way ;)
Code:

#!/bin/bash

if [ -n "$1" ]
then
  for (( i=1; i<=$#; i++ ))
  do
    ps aux | egrep -v 'psfind|grep' | eval grep $`echo $i`
  done
else
  echo -e "\npsfind v0.3"
  echo -e "\tUsage: psfind process1 process2 ...\n"
fi

I did change the 'i=0; i<....' to 'i=1; i<=......'. Otherwise you will start with the name of the program itself ($0) before the parameters you suplied.

cortez 12-08-2003 05:03 PM

Great!
 
Thanks! Didn't knoe about eval.

I'm a :newbie:

;)

bye

Luca


All times are GMT -5. The time now is 07:44 PM.