You are not logged in.

#1 2008-05-24 21:05:03

B-Con
Member
From: USA
Registered: 2007-12-17
Posts: 554
Website

Bash script expand ~

I'm trying to write a bash script to copy an array of specified files to a target directory. However, if I include a "~" in the path name of any of the files, cp fails to parse the ~.

My script:

#!/bin/bash

BU_DEST="/home/b-con/settings/config-backup"
BU_LIST=(
    "~/.config"
    )

for file in $BU_LIST ; do
    cp -vr --parents -t $BU_DEST $file
done

This is the output

$ ./bu
cp: failed to get attributes of `~': No such file or directory

What I'm missing has to be very simple.

Offline

#2 2008-05-24 22:17:13

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Bash script expand ~

It's simple indeed. The answer is in the bash man page under tilde expansion: "If a word begins with an unquoted tilde character... etc"

Offline

#3 2008-05-24 22:22:54

pelle.k
Member
From: Åre, Sweden (EU)
Registered: 2006-04-30
Posts: 667

Re: Bash script expand ~

pelle@nemo:~$ h=( "~" "$HOME" )
pelle@nemo:~$ echo ${h[0]}
~
pelle@nemo:~$ echo ${h[1]}
/home/pelle
pelle@nemo:~$ h=( ~ $HOME )
pelle@nemo:~$ echo ${h[0]}
/home/pelle
pelle@nemo:~$ echo ${h[1]}
/home/pelle

So you want to remove the quotation marks when setting home, unless you do use  $HOME/.config instead.
Strange stuff, i know.


"Your beliefs can be like fences that surround you.
You must first see them or you will not even realize that you are not free, simply because you will not see beyond the fences.
They will represent the boundaries of your experience."

SETH / Jane Roberts

Offline

#4 2008-05-24 22:30:47

B-Con
Member
From: USA
Registered: 2007-12-17
Posts: 554
Website

Re: Bash script expand ~

Ah, I see. No using quotes causes it to be evaluated on the spot, rather than in the string later. Removing the quotes from the array does it for that example.

Unfortunately, I have other paths like "~/.gtk-2.0" that need quotes. So I guess I'll just replace $file with ${file/#~/$HOME}.

Thanks guys.

Last edited by B-Con (2008-05-24 22:33:30)

Offline

#5 2008-05-25 11:50:27

T-Dawg
Forum Fellow
From: Charlotte, NC
Registered: 2005-01-29
Posts: 2,736

Re: Bash script expand ~

try:

HOME=$(echo ~)

Offline

Board footer

Powered by FluxBB