0

Hope you are doing well. I am kind of new to bash scripting so I wanted to ask you a question on something I stumbled upon just recently when I was playing around with the find command. What I had noticed was that when I search for a script name using the find command using the command substitution in the bash script, and call the variable from command substitution, it will find the script full path and also execute it right after. Can you please let me know why and how this is working? E.g.

SEARCH=$(find / -type f -iname "script.name" 2> /dev/null)
$SEARCH

Regards

3
  • The question is unclear. find prints the full path of the script and assigns it to SEARCH. The line $SEARCH executes the script. Commented Aug 31, 2022 at 18:34
  • Hi William, Thanks you very much for the reply. I just wanted to know why the '$SEARCH' would execute the command from the find command. Commented Aug 31, 2022 at 18:55
  • If $SEARCH expands to /path/to/script, then writing $SEARCH is (basically) the same as writing /path/to/script. bash parses the line and attempts to execute it. Commented Aug 31, 2022 at 19:01

1 Answer 1

2

Bash performs expansions before it builds and executes the command. If you execute cd "$HOME" for example, you probably want to go to the directory stored in the variable HOME and not to a directory literally named $HOME. This allows you to put a command name inside a variable and run it by expanding the variable as the first word, although this isn't really recommended because it becomes very complex to manage for anything more than the simplest commands. The code in your question would probably not work as intended if find returned multiple results for example.

See BashParser on the BashFAQ.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi tjm, Thank you very much for the reply. Your answer makes a perfect sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.