Don't understand $1 in shell scripts

Get help. Get answers. Let others lend you a hand.

Moderator: Mr_Noodle

Don't understand $1 in shell scripts Mon Sep 14, 2009 4:15 pm • by zoara
Hi,

I can't work out how to use $1 in shell scripts.

If I have a script that (say) matches filename "foo.txt", I can trigger an embedded shell script
Code: Select all
cp foo.txt bar.txt
and it all works well.

But if I try to use $1 in the script, like so:
Code: Select all
cp $1 bar.txt

then the logs show that the attempt just throws back a "usage" message for cp.

So what am I doing wrong?

(NB, this is a simplified example, I'm not really trying to use cp!)
zoara
 
Posts: 3
Joined: Mon Sep 14, 2009 4:01 pm

Re: Don't understand $1 in shell scripts Mon Sep 14, 2009 4:31 pm • by zoara
Actually, I'd like to ask an additional question; given a filename, how do I use $1 as a reference to build a different filename?

Continuing my "it's just an example, I'm not really using cp" theme, how would I rewrite the hard-coded
Code: Select all
cp foo.txt hellofoo.txt

so that it copied bar.txt to hellobar.txt, baz.txt to hellobaz.txt, etc etc?
zoara
 
Posts: 3
Joined: Mon Sep 14, 2009 4:01 pm

Re: Don't understand $1 in shell scripts Tue Sep 15, 2009 12:28 pm • by Mr_Noodle
$1 represents the file path that is being processed. One general tip with shell scripts is to quote it like so:

cp "$1" bar.txt

That ensures if the file has spaces that it will still be considered one argument and not many (since arguments are normally separated by spaces). Not sure if that is your problem but it's something to check.
Mr_Noodle
Site Admin
 
Posts: 8571
Joined: Sun Sep 03, 2006 1:30 am
Location: New York City

Re: Don't understand $1 in shell scripts Tue Sep 15, 2009 5:27 pm • by zoara
Thanks, that works! It's odd because, in this circumstance, there are no spaces in the filenames. But it works, so I'm happy... Cheers.
zoara
 
Posts: 3
Joined: Mon Sep 14, 2009 4:01 pm


Return to Support