0

so i have a line of code like:

list=$(find . -maxdepth 1 -name "$1" -print0 | sed 's,\.\/,,g')
echo $list

so in terminal when i do bash script_name string

i hope it will display all the files that contain "string"

Now in a folder i have 4 matches : TesT1.c TesT1.h TesT2.c TesT2.h

when i do

bash script_name TesT*

my code only return the first match ,which is TesT1.c

Where did i do wrong, thank you in advance

2 Answers 2

1

When you do:

bash script_name TesT*

bash expands TesT* at the time of calling your script and makes it:

bash script_name TesT1.c TesT1.h TesT2.c TesT2.h

Since you're only using $1 you just get: TesT1.c

You need to call you script as

bash script_name 'TesT*'

to avoid expansion of glob pattern (due to use of single quote)

Sign up to request clarification or add additional context in comments.

2 Comments

Hi is there any other way i can make it work instead of quoting in terminal? like can i do sth to my script?
Another way is to just call it as: bash script_name TesT and then use find command as: find . -maxdepth 1 -name "$1*"
0

When you run bash script_name TesT* your current shell expands the glob so your run command is actually bash script_name TesT1.c TesT1.h TesT2.c TesT2.h.

Your script then uses $1 (the first argument) and runs

find . -maxdepth 1 -name "TesT1.c" -print0 | sed 's,\.\/,,g'

which obviously only finds itself.

Quote the glob on the initial command line.

bash script_name 'TesT*'

Also there's no reason to stuff the output from find into a variable and then echo it back out like that.

3 Comments

Hi, what can i do to my script to make it work? I don't want to quote in terminal command. :) But thank you for helping me.
The only way to get this to work from the command line without quoting is to disable pathname expansion with set -f. So set -f; bash script_name TesT*; set +f (also a shell function is likely better for this than a separate script).
This is one of the assignment and i need to write it in a shell script lol. Anyway i think i need to find a better way to do this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.