0

I'm trying to count the number of files with different extensions in /foo/. case 1 works as expected, but more flexible situations such as case 2 or case 3 don't work as expected.

File test.sh

# case 1
vista=$(find /foo/*.zip -atime -1)
echo "$vista" | wc -l

# case 2
vista=$(find /foo/*)

echo "$vista.zip -atime -1" | wc -l

# case 3
echo "$vista.xz -atime -1" | wc -l

Output:

./test.sh 
187
4566
4566

I suspect the problem is that for example echo "$vista.zip -atime -1" from case 2 runs first find /foo/* before appending the string zip -atime -1, but I don't know how to do it right.

4
  • 2
    See BashFAQ #50 Commented Apr 24, 2019 at 16:25
  • See Is it OK for users to edit the accepted answer into the question?. For a Community Wiki answer (which isn't owned by any individual but open for anyone to edit with no individual getting rep points / credit), feel free to add your refinements to that answer itself. Commented Apr 24, 2019 at 17:04
  • Following @Charles Duffy's advise, a solution with functions is: find_under_foo() { find /foo/*"$1" "${@:2}"; } find_under_foo zip -atime -1 | wc -l Commented Apr 24, 2019 at 17:24
  • Also, vista=$(find /foo/*) doesn't do anything like storing a command in the variable, it runs the command and stores its output in the variable. So it might set vista to something like "/foo/file1\n/foo/file2" (where the \n represents an actual newline character). Then echo "$vista.zip -atime -1" | wc -l expands to echo "/foo/file1\n/foo/file2.zip -atime -1" | wc -l which isn't even slightly close to what you want. Commented Apr 24, 2019 at 20:14

1 Answer 1

1

Code should never be stored in strings (unless using printf %q to generate eval-safe versions of variables, and then using eval at runtime). Use either an array (for dynamically-constructed content) or a function.

The former:

find_cmd=( find /foo/* )
"${find_cmd[@]}" -atime -1 | wc -l

The latter:

find_under_foo() { find /foo/* "$@"; }
find_under_foo -atime -1 | wc -l
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.