HattrickNZ
HattrickNZ

Reputation: 4643

changing to current directory where file.sh is located using variable

I want a script that changes directory to the directory where the file.sh is located, lets say var1.
Then I want to copy files from another location ,lets say var2, to the current dir which would be var.
Then I want to do some unzipping and deleting rows in the files, which would be in var

I have tried the below, but my syntax is not correct. Can someone please advise?

#!/bin/bash
# Configure bash so the script will exit if a command fails.
set -e 

#var is where the script is stored
var="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd";
#another dir I want to copy from
var2 = another/directory

#cd to the directory I want to copy my files to 
cd "$var" + /PointB  

#copy from var2 to the current location
#include the subdirectories 
cp -r var2 .

# This will unzip all .zip files in this dir and all subdirectories under this one.
# -o is required to overwrite everything that is in there
find -iname '*.zip' -execdir unzip -o {} \;

#delete specific rows 1-6 and the last one from the csv file
find ./ -iname '*.csv' -exec sed -i '1,6d;$ d' '{}' ';'

Upvotes: 0

Views: 137

Answers (1)

glenn jackman
glenn jackman

Reputation: 246754

a few mistakes here:

# no: var="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd";
var=$(cd "$(dirname "$0") && pwd)

The stuff in $() executes in a subshell, so the "pwd" must be performed in the same shell that you have "cd"-ed in.

# no: var2 = another/directory
var2=another/directory

The = cannot have whitespace around it.

# no: cd "$var" + /PointB  
cd "$var"/PointB  

shell is not javascript, string contatenation does not have a separate operator

# no: cp -r var2 .
cp -r "$var2" .

Need the $ to get the variable's value.

# no: find -iname '*.zip' -execdir unzip -o {} \;
find . -iname '*.zip' -execdir unzip -o {} \;

Specify the starting directory as the first argument to find.

Upvotes: 1

Related Questions