Is it possible to use the source command multiple times on different files? [closed] - linux

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I currently try to write a bash script which should help me to automate the virtual enviroments in python alittle bit.
The problem is that it seems that I am not able to source twice. (Sourcing in a bash script another bash script).
These are the files which I use:
#!/bin/bash
# Call this file with . filename or source filename to run it in the current bash
if [ "$#" -eq 1 ]
then
if [ "$1" == "install" ]
then
pip install kivy[base]
# Install Kivy and some examples
#python -m pip install kivy[base] kivy_examples
elif [ "$2" == "start" ]
then
source ../virtualEnviroment.sh Kivy
fi
fi
virtualEnviroment.sh:
#!/bin/bash
# Call this file with . filename or source filename to run it in the current bash
ENVIROMENTNAME=$1
DIR=$1
(return 0 2>/dev/null) && sourced=1 || sourced=0
if [ "$#" -ne 1 ]
then
echo Missing enviromentname
else
if [ "$sourced" -eq 1 ]
then
if [ -d "$DIR" ]
then
echo Using existing enviroment $ENVIROMENTNAME
source "$ENVIROMENTNAME"/bin/activate
else
echo Creating new enviroment $ENVIROMENTNAME
python3 -m virtualenv "$ENVIROMENTNAME"
source "$ENVIROMENTNAME"/bin/activate
fi
else
echo Please use . $0 or source $0
fi
fi
Did I do something wrong, or is it normal that I only can source one time?
(Does it try to use the bash environment of the first bash script, but since it is already sourced, it can not use the sourced bash environment and use the unsourced bash environment of the first bash script?)

It seems I just forgot to add another source to the bash script to source the second bash file too.

Related

Environment variable not setting up after running bash script [duplicate]

This question already has answers here:
Setting environment variable in shell script does not make it visible to the shell
(2 answers)
Closed 4 months ago.
I am writing a bash script to automate the task of setting environment variables for my project. but when I execute my bash script using sh env.sh (env.sh is my file name). I am able to get value from the AWS secret manager and when I do echo inside the bash script I am able to print the env variable but when I run the echo $variable after the bash file is executed then it returns nothing.
I tried replacing eval to source but no luck
also i searched on stackoverflow for the issue but none of them helped.
find the script below
#! /usr/bin/env bash
if [[ "$OSTYPE" == "darwin"* ]]; then
echo 'running'
if ! [ -x "$(command -v aws)" ]; then
echo 'Aws is not installed. Installing aws............................' >&2
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
if ! [ $(id -u) = 0 ]; then
echo "The script need to be run as root." >&2
exit 1
fi
sudo installer -pkg AWSCLIV2.pkg -target /
if ! [ -x "$(command -v aws)" ]; then
echo 'There was some issue installing aws cli. Install aws-cli manually and then run the script!!!' >&2
exit 1
fi
echo "Running aws command please enter the aws access key and secrect"
aws configure
fi
aws secretsmanager get-secret-value --secret-id abc --query SecretString --output text | jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' > /tmp/secrets.env
eval $(cat /tmp/secrets.env | sed 's/^/export /')
fi
I am currently running this bash file on Mac OS, but I would like it to operate on any OS.
If the file contained enviroment variable names setup_local_env.sh, Try
source setup_local_env.sh
This will add them to your current session.
There is another solution called dot source. Check the reference here
. ./setup_local_env.sh
The reason if you directly run ./setup_local_env.sh, it does not work, is because it creates a new bash process, and sets the environment variable there, and then it's lost once the new bash process exits.

Automated script install using bash [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 3 years ago.
Improve this question
I'm trying to script install the below, how can I answer "y" at the prompt within the command
wget -O - mic.raspiaudio.com | sudo bash
I have tried the usual but this wont work
echo "y" | wget -O - mic.raspiaudio.com | sudo bash
Disclaimer: The solution below works for script that have a non-interactive switch.
I believe the echo won't work on this because it's not writing to the /dev/tty that the bash spawned. You can do it using the default feature bash provides.
From the man page:
-c If the -c option is present, then commands are read from the first
non-option argument command_string. If there are arguments after the
command_string, the first argument is assigned to $0 and any remaining
arguments are assigned to the positional parameters.
If you use -c option with bash, you can supply args to script that will run and those will be placed as mentioned in the man page. eg:
bash -c "script" "arg0" "arg1" .... The arg0 will be placed in $0 and arg1 will be placed in $1 and so on.
Now, I don't know if this can be generalized, but this solution will only work if there is a non-interactive mode in the script.
If you see the script it has the following function:
FORCE=$1
confirm() {
if [ "$FORCE" == '-y' ]; then
true
else
read -r -p "$1 [y/N] " response < /dev/tty
if [[ $response =~ ^(yes|y|Y)$ ]]; then
true
else
false
fi
fi
}
And is used as :
if confirm "Do you wish to continue"
then
echo "You are good to go"
fi
So, if we can set the $1 to "-y" it won't ask for a confirmation, We will try to do that same by:
$ bash -c "$( wget -qO - mic.raspiaudio.com)" "dummy" "-y"
This should work for the script, provided it does not have any other interactive options. I have not tested the original script by my own minimal script and it seems to work. eg:
$ bash -c "$(wget -qO - localhost:8080/test.sh)" "dummy" -y
You are good to go
$ bash -c "$(wget -qO - localhost:8080/test.sh)"
Do you wish to continue [y/N] y
You are good to go

How to write a "bash script.sh argument " [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
hi can someone help me with this.
How to Write a script that takes in as argument a filename and displays its modification date and time in this way exactly :
[user#localhost...]$ bash script.sh temp.txt
the file temp.txt was modified on May 1 20:20
And then modify that script in such a way that it lists the modification dates for directories whose names contain a given pattern in this way exactly :
[user#local....]$ bash script.sh testRegex Pub
the file testRegex was modified on May 1 20:22
the directory /home/user/Public was modified on Dec 26 08:00
the directory /home/user/Pubs. was modified on May 2 20:00
please help I need to answer this fast
Thanks
This is pretty simple to do actually. You should read up on the stat command as #John Bollinger said. I also used the date command to format the date. You can read up on taking arguments for a script here
Combining all of this would give -
#!/bin/bash
filename=$1;
dirname=$2;
file_mod_date=`date -d #$( stat -c %Y $1 ) +%m" "%B" "%H:%M`;
echo "The file ${filename} was modified on ${file_mod_date}";
if [ "$2" == "" ]; then
exit 1;
else
for i in /home/user/*${dirname}*/; do
dir_mod_date=`date -d #$( stat -c %Y $i ) +%m" "%B" "%H:%M`;
echo "The directory ${i} was modified on ${dir_mod_date}";
done
fi
A good way to do this is with passing options and values:
For example:
file_name=""
help_message="To use this script type script.sh --file /path/to/file.txt"
# -- Get input options (if any)
while [[ $# > 0 ]] ;do
key="$1"
case ${key,,} in
-f|--file)
file_name="${2,,}"
shift
;;
-h|--help)
echo -e "$help_message"
exit;
shift
;;
esac
shift
done
Call the script like this:
bash script.sh -f "temp.txt"
With regard to the "logic" of the script, you will have to figure that out ;-)

simplifying bash code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I have following code in a shell script. It is all working fine.
#!/bin/bash
baseDirPath = '/stackoverflow/question'
newDir = '/stackoverflow/question/answers'
# first check some business condition
if [[ some condition here ]]
then
# check if base Directory path already exit
if [ -d $baseDirPath ];then
# check if new Directory exits or not, if not create one
if [ ! -d $newDir ];then
mkdir $newDir
if [ $? -ne 0 ] ; then
echo "error occurred while creating directory "
fi
fi
else
exit 1;
fi
fi
This is very confusing and not very clean code i feel.
I am very new to programming so not sure how it can be clean.
I am very curious if it can be made simpler or there is some other way to do this.
(The complete shell script is not shown above, just the complicated if-else part is illustrated.)
#!/bin/bash
die(){ >&2 printf '%s\n' "$#"; exit 1; }
#Can't have spaces here
baseDirPath='/stackoverflow/question'
newDir='/stackoverflow/question/answers'
# first check some business condition
if [ some condition here ]; then
# check if base Directory path already exit
mkdir -p "$newDir" || die 'error occured while creating directory'
fi
This changes the semantics slightly--it exits if the creation of newDirs fails for whatever reasons -- baseDirPath is not a directory or baseDirPath is a directory and newDir cannot be created.
You can probably get rid of that error message too. mkdir will already give you an error on stderr if it fails for some reason:
mkdir -p "$newDir" || exit 1
If most of your commands should work like this (i.e., either succeed or bring down the whole script), then you're probably better off setting set -e (~ exit when a command returns with a nonzero status) and then just doing:
mkdir -p "$newDir"
This can be pretty thoroughly simplified:
#!/bin/bash
baseDirPath='/stackoverflow/question'
newDir='/stackoverflow/question/answers'
# first check some business condition
if [[ some condition here ]]; then
if ! mkdir -p "${newDir}"; then
echo "Unable to create directory ${newDir}. Aborting."
exit 1
fi
# Proceed as normal
fi
If you really do need for the baseDirPath to exist, then that can certainly be added as a condition:
if [[ ! -d "${baseDirPath}" ]] || ! mkdir -p "${newDir}"; then

Check if file exist Linux bash [duplicate]

This question already has answers here:
How do I tell if a file does not exist in Bash?
(20 answers)
Difference between ./ and ~/
(6 answers)
Closed 2 years ago.
So I'm trying to check if a file exists or not and then the script is supposed to do something if it does. The problem I'm having is actually getting it to recognize that something is actually there.
if [ -e /temp/file.txt ]; then
echo "file found!"
sudo cp -r temp/* extra
else
echo "file not found! Creating new one..."
./create.sh
fi
below is an example of the files in the directory I'm testing. they are clearly there, but for some reason I can't get the script to see that. what am I doing wrong?
nima#mkt:/docs/text$ ls -a temp
. .. more file.txt file2.txt
You are using absolute paths in your test while you should be using relative paths:
if [ -e ./temp/file.txt ]; then
/temp/file.txt vs /docs/text/temp/file.txt?
You script looks in /temp while you are looking in /docs/text/temp

Resources