Issue
I am writing a bash script named safeDel.sh with base functionalities including:
For the single letter arguments I am using the built in function getops which works fine. The issue I'm having now is with the 'file' argument. The 'file' argument should take a list of files to be moved to a directory like this:
$ ./safeDel.sh file file1.txt file2.txt file3.txt
The following is a snippet of the start of my program :
#! /bin/bash
files=("$@")
arg="$1"
echo "arguments: $arg $files"
The echo statement shows the following:
$ arguments : file file
How can I split up the file argument from the files that have to be moved to the directory?
Solution
Assuming that the options processed by getopts
have been shifted off the command line arguments list, and that a check has been done to ensure that at least two arguments remain, this code should do what is needed:
arg=$1
files=( "${@:2}" )
echo "arguments: $arg ${files[*]}"
files=( "${@:2}" )
puts all the command line arguments after the first into an array called files
. See Handling positional parameters [Bash Hackers Wiki] for more information.
${files[*]}
expands to the list of files in the files
array inside the argument to echo
. To safely expand the list in files
for looping, or to pass to a command, use "${files[@]}"
. See Arrays [Bash Hackers Wiki].
Answered By - pjh Answer Checked By - Clifford M. (WPSolving Volunteer)