Amber
Amber

Reputation: 944

Partial File Name as Shell Script Input

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?

Upvotes: 0

Views: 873

Answers (1)

KamilCuk
KamilCuk

Reputation: 141708

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.

Upvotes: 1

Related Questions