mon
mon

Reputation: 22388

Cannot create directory with sudo

Question

Why sudo cannot create a directory with the error?

USER=ansible

AUTH_KEY_DIR="$(sudo -i -u ${USER} pwd)/.ssh"
AUTH_KEY_FILE="${AUTH_KEY_DIR}/.ssh/authorized_keys"

# ERROR >-bash: mkdir /home/ansible/.ssh: No such file or directory
sudo -i -u ${USER} "mkdir ${AUTH_KEY_DIR}"   # <----- Error is caused here. 
sudo -i -u ${USER} "touch ${AUTH_KEY_FILE}"

Solution

sudo -i -u ${USER} /bin/bash -c "mkdir ${AUTH_KEY_DIR}"  

Upvotes: 1

Views: 730

Answers (1)

KamilCuk
KamilCuk

Reputation: 141940

Too much qouting. The sudo command does not re-tokenize the commands:

sudo -i -u ${USER} mkdir "${AUTH_KEY_DIR}"

It cannot create directory the same way running:

"mkdir ${AUTH_KEY_DIR}"

will try to find a executable named mkdir ${AUTH_KEY_DIR} and run it. You want to run mkdir with an argument ${AUTH_KEY_DIR}.

Upvotes: 3

Related Questions