Naveen Pandey
Naveen Pandey

Reputation: 23

Quoting a path in linux

I am learning shell scripting and created a script. In the script I have assigned find command output to a variable in my code. But reviewer commented that "paths need quoting since they contain variables that need to be expanded". I am not getting this.

MAIN_PROFILE="$(find /Users/$CURRENT_USER/Library/Group\ Containers/*.Office -type d -name "Main Profile")"

Upvotes: 1

Views: 307

Answers (1)

Paul
Paul

Reputation: 305

You could quote $CURRENT_USER like this :

MAIN_PROFILE="$(find /Users/"$CURRENT_USER"/Library/Group\ Containers/*.Office -type d -name "Main Profile")"

You need to do it to prevent word splitting or globbing (See https://github.com/koalaman/shellcheck/wiki/SC2086)

For example with a script like this :

#!/bin/bash
USER="jean claude"
find /home/"$USER"/ -type d -name "test"

It will work perfectly.

But if you unquote it :

find: ‘/home/jean’: No such file or directory
find: ‘claude/’: No such file or directory

You could also quote the full path as your reviewer said, so you wouldn't have to escape spaces :

MAIN_PROFILE="$(find "/Users/$CURRENT_USER/Library/Group Containers/"*.Office -type d -name "Main Profile")"

Upvotes: 2

Related Questions