Tony Ruth
Tony Ruth

Reputation: 1408

Using $ notation in middle of C-Shell statement

I have a bunch of directories to process, so I start a for loop like this:

foreach n (1 2 3 4 5 6 7 8)

Then I have a bunch of commands where I am copying over a few files from different places

cp file1 dir$n
cp file2 dir$n

but I have a couple commands where the $n is in the middle of the command like this:

cp -r dir$nstep1 dir$n

When I run this command, the shell complains that it cannot find the variable $nstep1. What i want to do is evaluate the $n first and then concatenate the text around it. I tried using `` and (), but neither of those work. How to do this in csh?

Upvotes: 0

Views: 53

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295629

In this respect behavior is similar to POSIX shells:

cp -r "dir${n}step1" "dir${n}"

The quotes prevent string-splitting and glob expansion. To observe what this means, compare the following:

# prints "hello * cruel * world" on one line
set n=" * cruel * "
printf '%s\n' "hello${n}world"

...to this:

# prints "hello" on one line
# ...then a list of files in the current directory each on their own lines
# ...then "cruel" on another line
# ...then a list of files again
# ... and then "world"
set n=" * cruel * "
printf '%s\n' hello${n}world

In real-world cases, correct quoting can thus be the difference between deleting the oddly-named file you're trying to operate on, and deleting everything else in the directory as well.

Upvotes: 2

Related Questions