Reputation: 2419
How can I use the relative path or absolute path as a single command line argument in a shell script?
For example, suppose my shell script is on my Desktop and I want to loop through all the text files in a folder that is somewhere in the file system.
I tried sh myshscript.sh /home/user/Desktop
, but this doesn't seem feasible. And how would I avoid directory names and file names with whitespace?
myshscript.sh contains:
for i in `ls`
do
cat $i
done
Upvotes: 1
Views: 2564
Reputation: 753695
Superficially, you might write:
cd "${1:-.}" || exit 1
for file in *
do
cat "$file"
done
except you don't really need the for
loop in this case:
cd "${1:-.}" || exit 1
cat *
would do the job. And you could avoid the cd
operation with:
cat "${1:-.}"/*
which lists (cat
s) all the files in the given directory, even if the directory or the file names contains spaces, newlines or other difficult to manage characters. You can use any appropriate glob pattern in place of *
— if you want files ending .txt
, then use *.txt
as the pattern, for example.
This breaks down if you might have so many files that the argument list is too long. In that case, you probably need to use find
:
find "${1:-.}" -type f -maxdepth 1 -exec cat {} +
(Note that -maxdepth
is a GNU find
extension.)
Avoid using ls
to generate lists of file names, especially if the script has to be robust in the face of spaces, newlines etc in the names.
Upvotes: 2
Reputation: 123460
Use a glob instead of ls, and quote the loop variable:
for i in "$1"/*.txt
do
cat "$i"
done
PS: ShellCheck automatically points this out.
Upvotes: 1