Yakov Dan
Yakov Dan

Reputation: 3347

$_ variable in script does not work as expected

I have c shell script that sources another:

source ./sc1.csh param

the script being sourced does the following:

set scriptName=($_)
if ( "$scriptName" == "" ) then
    set scriptName=$0
    echo "@**E: Please source this script, DO NOT RUN!"
    echo "ERROR"
    exit 1
else
    set scriptName=`basename $scriptName[2]`
endif

I expect $_ to contain "source ./sc1.csh param". However, it is actually empty. Manually running

source ./sc1.csh param

in the shell results in the correct, expected behavior. What's going on?

Thanks.

Upvotes: 1

Views: 113

Answers (2)

Yakov Dan
Yakov Dan

Reputation: 3347

Ok, so as user1717259 pointed out, $_ substitutes the command line of the last executed command, thus making it inappropriate for inspecting the command line inside the script being called. Instead, using $* (alias of $argv) works, as it contains all of the command line except for "source" itself.

Upvotes: 1

user1717259
user1717259

Reputation: 2863

From man csh

$_

Substitutes the command line of the last command executed. (+)

As the script has not completed execution yet, then $_ hasn't been set.

What happens if you call the script again?

Upvotes: 1

Related Questions