Vidya
Vidya

Reputation: 657

Bash script string with spaces arguments is not working

Bash arguments with space not working, even I am using quotes in aruments

update_config_entry() {
  echo
  echo -e "${RED}CONFIG-UPDATE${NC} Ensure $1 is updated in $2"

  if grep -Fx $1 $2; then
    echo "$1 already exist in file $2"
  else
    echo $1 >> $2
  fi

  policystatus=$?

  if [[ "$policystatus" -eq 0 ]]; then
    echo -e "${GREEN}Remediated:${NC} Ensure $1 is updated in $2"
  else
    echo -e "${RED}UnableToRemediate:${NC} Ensure $1 is updated in $2"
fi

}

update_config_entry "install usb-storage /bin/true" /etc/modprobe.d/CIS.conf 

Error:

grep: usb-storage: No such file or directory
grep: /bin/true": No such file or directory

"install usb-storage /bin/true" should go single argument but it is passing install usb-storage /bin/true as separate arument. what I am doing wrong,

other places recomended enclose with quotes and I am already doing it

Link

Bash script GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

Upvotes: 0

Views: 237

Answers (3)

Dudi Boy
Dudi Boy

Reputation: 4900

Suggesting fix:

update_config_entry() {
  echo
  echo -e "${RED}CONFIG-UPDATE${NC} Ensure $1 is updated in $2"

  if [[ $(grep -Fxc "$1" "$2") -ne 0 ]]; then
    echo "$1 already exist in file $2"
  else
    echo "$1" >> "$2"
  fi

  policystatus=$?

  if [[ "$policystatus" -eq 0 ]]; then
    echo -e "${GREEN}Remediated:${NC} Ensure $1 is updated in $2"
  else
    echo -e "${RED}UnableToRemediate:${NC} Ensure $1 is updated in $2"
fi

}

update_config_entry "install usb-storage /bin/true" /etc/modprobe.d/CIS.conf 

Upvotes: 0

Dominique
Dominique

Reputation: 17551

I'm afraid that your double quotes are not sufficient. I tried the following:

update_config_entry """install usb-storage /bin/true""" /etc/modprobe.d/CIS.conf

It looked quite well.

Upvotes: 0

user1934428
user1934428

Reputation: 22291

You forgot to quote the argument to grep. It should be

grep -Fx "$1" "$2"

otherwise grep receives

grep -Fx install usb-storage /bin/true /etc/modprobe.d/CIS.conf 

which means that it is asked to search the file usb-storage.

Upvotes: 1

Related Questions