Zet - Bash: Split String into Command and Args

Bash: Split String into Command and Args

When you have a string like "clamscan --recursive" and need to separate it into command + args:

first_field="clamscan --recursive"  
  
# Split string into array (words split on whitespace)  
read -ra cmd_parts <<< "$first_field"  
  
# Get command (first element)  
cmd="${cmd_parts[0]}"  
  
# Get args (all elements from index 1 onwards)  
args=("${cmd_parts[@]:1}")  
  
# Execute with args  
exec "$cmd" "${args[@]}"  

Key Syntax

SyntaxMeaning
read -ra-a puts words into array, -r prevents backslash escaping
<<<Here-string: feeds string as input to command
"${cmd_parts[0]}"First element of array
"${cmd_parts[@]:1}"Slice array from index 1 to end
"${args[@]}"Expands array elements as separate words

This preserves args with spaces correctly (e.g., "foo bar" stays as one arg).

#bash