Bash: preventing variable evaluation

I have a variable that stores the directory path (optional owner, group) and permissions, separated by pipe:

line='/opt/temp/dir/*|||a+r'

      

If I echo $line

I get the directory substring the way I expect and need:

~ /opt/temp/dir/*|||a+r

      

So now I need to parse this string and assign its directory component to the appropriate variable, something like this:

DIR=$(echo $line | awk -F "|" '{print $1}')

      

The problem is that when I iterate $DIR

, I get the whole list of subdirectories from behind *

.

~ # echo $DIR
/opt/oracle/asa_test/a1 
/opt/oracle/asa_test/a2 
/opt/oracle/asa_test/a3 
/opt/oracle/asa_test/test123

      

but I need to get exactly the substring /opt/temp/dir/*

:

 echo $DIR
 ~ # /opt/temp/dir/*

      

As you can see, it $line

is evaluated inside a variable $DIR

. How can I avoid this and get exactly the first substring in the variable $DIR

up to the first pipe including *

?

+3


source to share


2 answers


Double quoting your variables to avoid Pathname Expansion

in bash

likeecho "$DIR"

On the page man bash



Path name expansion

After splitting words, if -f

not set, bash scans each word for characters *

, ?

and [

. If one of these characters appears, that word is treated as a pattern, and is replaced with an alphabetically sorted list of filenames matching the pattern.

+2


source


You don't need awk

for this simple task:

line='/opt/temp/dir/*|||a+r'
echo "${line%%|*}"

      


If you want to split the string into characters |

, use:



IFS='|' read -r -a fields < <(printf '%s|\0' "$line")

      

This will fill the array with the fields

fields of your string: the command declare -p fields

will output:

declare -a fields='([0]="/opt/temp/dir/*" [1]="" [2]="" [3]="a+r")'

      

+1


source







All Articles