0

I am trying to create a shell script that takes a partial file name as its input and then does operations on the files with the matching names. For example, I have three files sample1.txt,sample2.txt and sample3.txt and this is my script

#!bin/bash

VALUE=$1
VALUE2=$2
FILE_NAME=$3

echo $FILE_NAME

And I run it with this command

sh myscript.sh arg1 arg2 sample*

But I get this as the output

sample3.txt (sample2.txt)

But what I want is

sample1.txt
sample2.txt
sample3.txt

How could I do this?

4
  • 1
    You are passing an argument list from the sender (i.e. sample* could be any number of files). So use an array (list) at the receiver to get all the arguments ("$@") and not just the first Commented May 21, 2019 at 7:27
  • do FILE_NAME=("$@") and print the whole array i.e. printf '%s\n' "${FILE_NAME[@]}" Commented May 21, 2019 at 7:28
  • @InianWhat if I have other arguments too? I have edited the question Commented May 21, 2019 at 7:34
  • 1
    Use the shift command to shift the positional arguments. In your case to skip two arguments do shift 2; FILE_NAME=("$@") Commented May 21, 2019 at 7:39

1 Answer 1

1
sample*

get's expanded into (if the files exists, no more files with that name, etc):

sample1.txt sample2.txt sample3.txt

So when you write:

sh myscript.sh arg1 arg2 sample*

What you really write, what your script sees is:

sh myscript.sh arg1 arg2 sample1.txt sample2.txt sample3.txt

Your script get's 5 arguments, not 3

Then you can:

#!bin/bash

VALUE=$1
VALUE2=$2

# shift the arguments to jump over the first two 
shift 2

# print all the rest of arguments
echo "$@"

# ex. read the arguments into an array
FILE_NAME=("$@")
echo "${FILE_NAME[@]}"

Live example at jdoodle.

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

Comments

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.