I'm trying to make a bash
script that asks me a question and, if I respond y
, executes the subsequent scripts; but, if I respond n
, it terminates "ALL" of the subsequent script.
I already created the bash script, but when I respond with n
, the following scripts, build
and anotherBashScript
, are executed.
package.json
"scripts": {
"prebuild": "./ask.sh",
"build": "vite build",
"postbuild": "./anotherBashScript.sh"
},
ask.sh
read -p "Are you sure you want to build the app? (y/n) " yn
case $yn in
[yY] ) echo Building the app...
break;;
[nN] ) echo exiting...;
exit 1;;
* ) echo invalid response;;
esac
CodePudding user response:
The build script by definition will always follow the prebuild step. A way of achieving what you want is to have a file track the exit code and then wrap the vite build command in another bash script that first checks the file for the exit code before proceeding accordingly.
Example, using status.txt to track status:
"scripts": {
"prebuild": "./ask.sh",
"build": "./build.sh",
"postbuild": "./anotherBashScript.sh"
},
ask.sh
read -p "Are you sure you want to build the app? (y/n) " yn
case $yn in
[yY] ) echo Building the app...
break;;
[nN] ) echo exiting...;
echo 1 > status.txt;;
* ) echo invalid response;;
esac
build.sh
if [[ "$(cat status.sh)" == "1" ]]
then
exit 1
else
vital build
if [[ "$?" == "1" ]]
then
echo 1 > status.txt
exit 1
fi
fi
anotherBashScript.sh
if [[ "$(cat status.sh)" == "1" ]]
then
exit 1
else
...
fi
CodePudding user response:
Thanks Raman Sailopal.
I adapted your suggestion and applied it to write the following script, and it was successful!
package.json
"scripts": {
"prebuild": "./ask.sh",
"build": "./build.sh",
"postbuild": "./anotherBashScript.sh"
},
ask.sh
#! /bin/bash
read -p "Are you sure? (y/n) " yn
case $yn in
[yY])
echo Building the app...
echo 1 >status.txt
;;
[nN])
echo exiting...
;;
*) echo invalid response ;;
esac
build.sh
#! /bin/bash
if [[ "$(cat status.txt)" == "1" ]]; then
yarn run vite build
echo 1 >status.txt
exit 1
else
exit 1
fi
anotherBashScript.sh
#! /bin/bash
if [[ "$(cat status.txt)" == "1" ]]; then
# do stuff
rm status.txt
else
exit 1
rm status.txt
fi