0

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)

2
  • 2
    Run your script through shellcheck.net Commented Apr 27, 2022 at 4:55
  • It is passed to your string as a single argument. You can verify it if you do something like echo ">>>$1<<<" at the start of your function update_config_entry `. Commented Apr 27, 2022 at 6:30

3 Answers 3

1

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.

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

Comments

0

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.

1 Comment

The extra double-quotes don't do anything at all (each extra pair actually cancel each other out).
0

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 

Comments

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.