0

I want to feed in all input matching a pattern using wildcards. Example:

$ cat file_lister.sh
echo $1

$ ls *.txt
file1.txt
file2.txt
file3.txt

$ ./file_lister.sh ./*.txt
file1.txt

But I expected, my script to print

file1.txt
file2.txt
file3.txt
2
  • The echo will put all the names on one line. The scripted command should be: printf '%s\n' "$@" Apr 2 '20 at 19:50
  • The issue is that the shell running file_lister expands the wildcards, which go into the script as $1 $2 $3. If you single-quote the './*.txt' argument, it will be $1 to the command-line script and be expanded by the other shell that is running the script. Apr 2 '20 at 19:55
1

When you run your script:

$ ./file_lister.sh ./*.txt

The shell expands ./*.txt to ./file1.txt ./file2.txt ./file3.txt, so after the expansion you really end up executing:

$ ./file_lister.sh ./file1.txt ./file2.txt ./file3.txt

Your script prints the first argument:

echo $1

$1 corresponds to the first argument passed to the script, which in this case is ./file1.txt -- I'd expect to see that instead of just file1.txt (unless you really ran ./file_lister.sh *.txt).

As others have suggested in the comments, if you want to print all of the arguments instead of the first, there are number of things you can do. The easiest is to change $1 (the first argument) to $@ (all arguments).

#!/bin/bash
printf '%s\n' "$@"

See this question on Stack Overflow for more information on processing arguments in a script.

1
  • 1
    I believe they expect the output to be one name per line, in which case printf '%s\n' "$@" would be better than echo "$@", which outputs all the arguments with a space between each.
    – Kusalananda
    Jul 28 at 17:04

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.