Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

When I run the following command

./command *

using this script

#!/bin/bash

for f in ./$1
do
    echo $f
done

only the first file specified in $1 is echoed. My question is why?

share|improve this question
    
What are you trying to do? –  i08in Nov 11 '13 at 11:46
    
I want to resize images using the following syntax: scale 1024x768 *.jpg. When passing *.jpg as a parameter my script only processes the first file found. –  Hendre Nov 11 '13 at 11:54
add comment

3 Answers 3

up vote 1 down vote accepted

Because you didn't used simple or double quotes when you ran your command:

./command '*'

or:

./command "*"

Or, if you want certainly to use ./command *, then make the following modification in your script:

#!/bin/bash

for f in ./"$@"
do
    echo $f
done

That's because $1 refers to the first argument from your command ans $@ refers to all arguments from your command.

Read also some documentation in this sense: http://tldp.org/LDP/abs/html/internalvariables.html#APPREF

share|improve this answer
add comment

The shell expands the * when you run the command. So, running the script is equivalent to

./command file1.txt file2.txt file3.txt

$1 corresponds to the first argument, therefore the loop only has one iteration.

share|improve this answer
add comment

$1 only refers to the first argument. You need to use $*.

#!/bin/bash

for f in $*
do
     echo $f
done
share|improve this answer
    
No, never use $* unless you know exactly what it means. Use "$@" (with quotes) instead. –  gniourf_gniourf Nov 11 '13 at 12:04
    
@gniourf_gniourf: Your comment is not helpful because it does not provide substantial information. –  Clausi Nov 11 '13 at 12:13
    
My comments are never helpful. Oh, unless you're willing to learn the difference between $* and $@, in which case you can have a look at the references online. It's free, I've been told. For example this reference about Bash's special parameters. –  gniourf_gniourf Nov 11 '13 at 12:18
    
@gniourf_gniourf: Sorry, I already read this, but still do not understand the problem. I am willing to learn, but if your are not willing to explain, maybe your not at the right place. –  Clausi Nov 11 '13 at 12:35
    
$* is broken if you give parameters containing spaces. "$*" expands to just one word, so it's not good. The only possibility is "$@" (quoted) that will work regardless how funny the symbols are in the arguments. –  gniourf_gniourf Nov 11 '13 at 12:40
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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