0
sh temp1.sh Gold.txt Silver.txt
2
Gold.txt
$2

Silver is second to gold. It is a unique position in a competition.

cat: cannot open $2

tstetlx () /appl/edw/apps/scripts/scenario1> vi temp1.sh
i=$#
echo $i
echo $1
echo $`echo $i`
#cat "$`echo $i`"
cat $2
cat "\$$i"

The below command is not printing the contents of the second file passed as an argument to the file.

cat "\$$i"
Jens
  • 67,715
  • 15
  • 98
  • 113

2 Answers2

0

Not clear to me what you are trying to do. Consider using $1 or $2.

The reason that line fails is because the parameter for cat is literally $2 - no attempt by the shell to substitute $2 as if it were a variable.

This is one way to handle the problem. Note that this is a bash solution.

i=$#
echo $i
echo $1
echo $`echo $i`
#cat "$`echo $i`"
cat $2
cat "\$$i"
declare -a arr=( "$0" $@ )
echo  ${arr[i]}
cat ${arr[i]}
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
0

Make sure a file called Silver.txt exists in the same directory as temp1.sh.

As for the variable indirection you are trying to do with cat "\$$i", you want eval:

eval cat "\$$i"

However, eval can be dangerous. Make sure the variable you will be eval'ing is valid, especially if its contents comes from user input. Run this and see what I mean:

eval cat "\$$i;ps -ef"

It will run a command if it can be manipulated to contain one. See this post for a better discussion on why and alternatives: Why should eval be avoided in Bash, and what should I use instead?.

Community
  • 1
  • 1
Gary_W
  • 9,933
  • 1
  • 22
  • 40