-1

I'm writing a larger bash script, and I've found this snippet to test if a directory exists case insensitive

Now, if I now have one directory called subs this script will print the path, and if I have two (or more) it will print those too..

but I don't really understand how, since there is only 1 print function, and no loop?

I guess it has something to do with the '\t%s\n' "$@" code... someone that can explain this to me? (trying to understand)

dir=~/test1
shopt -s nullglob nocaseglob
set -- $dir/[s]ubs/
if [ "$#" -gt 0 ]; then
    echo 'There is at least one directory called "subs" (case ignored):'
    printf '\t%s\n' "$@"
fi
3

Shell printf uses the format as many times as it has args for. So it has a built-in loop.

If it had three % strings in the string, it would use three args at a time. The last time round, it will default one or two args to blank/zero if it needs to.

The "$@" expands all the $1, $2, ... current args to separate quoted strings.

In the print format (the first argument)

\t (escaped t) is a tab and will indent by 8 spaces.

%s takes the next unused arg and inserts it as a string.

\n (escaped n) is a newline and will make the next line start below and in column.

man bash is a command that shows you all built-in commands, including a couple of pages about printf.

man -s 1 printf is a command that shows you what the external command /bin/printf does. It is very similar to (but not identical to) the bash built-in, but a lot easier to find.

| improve this answer | |
  • but what does \t%s\n "$@" mean? \n = new line, – JoBe Aug 9 at 20:40
  • 1
    @alecxs I expanded my answer after JoBe's comment and before yours: my original was only the first 3 lines. The OP's profile is helpful. – Paul_Pedant Aug 10 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.