1

I am trying to execute the following code in shell but I am not getting the output as expected. The command is as follows:

i=1
echo $($i)

I am getting an error:

Command not found error

I think it should show the value of the first command line argument, rather it is giving error.

2

Because the construct $(...) is a command substitution, so $($i) means to run the contents of variable $i. In your case, it would try to execute 1, which the shell cannot find.

See below how it fails, but if we create a script named '1', it works.

Example:

$ i=1
$ echo "$($i)"
-bash: 1: command not found  
$ cat >1
#!/bin/bash
echo Hello World
$ chmod 755 1
$ PATH=$PATH:`pwd`
$ echo "$($i)"
Hello World
$

To display the value of the first command line argument, you need $1 or ${1}

$ cat >mytest
#!/bin/bash
echo "arg 1 is $1"
echo "arg 1 is ${1}"
$ chmod 755 mytest
$ ./mytest foo
arg 1 is foo
arg 1 is foo
$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.