简体   繁体   中英

BASH script returning command not found

I am very new to bash programming and wanted to create a script that would store each result of find individually into an array. Now I want the command variable to expand on the statement MYRA=($(${Command} $1))

Command = 'find . -iname "*.cpp" -o -iname "*.h"'
declare -a MYRA
    MYRA=($(${Command} $1))
echo ${#MYRA[@]} 

However when I try this script I get the result

$ sh script.sh
script.sh: line 1: Command: command not found
0

Any suggestions on how I can fix this ?

Shell assignment statements may not have whitespace around the = . This is valid:

Command='some command'

This is not:

Command = 'some command'

In the second form, bash will interpret Command as a command name.

All of the below requires a #!/bin/bash shebang (which should come as no surprise since you're using arrays, which are a bash-only feature).

Also, see http://mywiki.wooledge.org/BashFAQ/050 for comprehensive discussion.


A best-practices implementation would look something like this:

# commands should be encapsulated in functions where possible
find_sources() { find . '(' -iname '*.cpp' -o -iname '*.h' ')' -print0; }

declare -a source_files
while IFS= read -r -d '' filename; do
  source_files+=( "filename" )
done < <(find_sources)

Now, if you really need to store the command in an array (maybe you're building it up dynamically), doing that would look like this :

# store literal argv for find command in array
# ...if you wanted to build this up dynamically, you could do so.
find_command=( find . '(' -iname '*.cpp' -o -iname '*.h' ')' -print0 )

declare -a source_files
while IFS= read -r -d '' filename; do
  source_files+=( "filename" )
done < <("${find_command[@]}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM