GNU nano 2.7.4 File: /home/pi/initDisplay/initDisplay.sh
#!/usr/bin/env bash
#HDMI connection?
rm -f hdmi.name
tvservice -n 2>hdmi.name
HDMI_NAME=`cat hdmi.name`
echo $HDMI_NAME
if [ "$HDMI_NAME" == "[E] No device present" ]; then
LCD_ON=`cat /boot/config.txt | grep "#CONFIGURAZIONEHDMI"`
echo $LCD_ON
if [ "$LCD_ON" == "#CONFIGURAZIONEHDMI" ]; then
echo "reboot con la configurazione LCD"
sudo rm -f /boot/config.txt
sudo cp /boot/config_lcd.txt /boot/config.txt
sleep 2
sudo reboot -n
fi
else
HDMI_ON=`cat /boot/config.txt | grep "#CONFIGURAZIONELCD"`
echo $HDMI_ON
if [ $HDMI_ON == "#CONFIGURAZIONELCD" ]; then
echo "reboot con la configurazione HDMI"
sudo rm -f /boot/config.txt
sudo cp /boot/config_hdmi.txt /boot/config.txt
sleep 2
sudo reboot -n
fi
fi
Doesn't start the arg of if statement with $LCD_ON. When I try to execute it, it doesn't return what I expect. Now it returns:
[E] no device detected
#CONFIGURAZIONEHDMI
but it doesn't start to replace file and reboot.
P.S.: The user and the file have privileges to do it
And I already set chmod 777 the file
There might be more on the line that matches, such as extra whitespace, so the equality test doesn't match exactly.
If you want to test whether a matching line exists in a file, you can just test the exit status of grep, rather than storing the output in a variable.
if grep -q "#CONFIGURAZIONEHDMI" /boot/config.txt; then
echo "reboot con la configurazione LCD"
sudo rm -f /boot/config.txt
sudo cp /boot/config_lcd.txt /boot/config.txt
sleep 2
sudo reboot -n
fi
The -q option tells grep not to print the matching line, it just sets its exit status.
Related
animal_name=""
if [[ -z "${!animal_name// }" ]]; then
animal_name="doggo"
fi
echo sudo chmod ...... ${!animal_name}
Is there any way to reference a variable in bash?
Ditch the "{}"
animal_name=""
if [[ -z "$animal_name" ]]; then
animal_name="doggo"
fi
sudo chmod {flag} $animal_name
I think your error is in line 3 (or 2, depending on how you look at it.)
animal_name=""
if [[ -z "${!animal_name// }" ]]; then # Error: event not found: animal_name//
animal_name="doggo"
fi
echo sudo chmod ...... $animal_name
The fix that I found was to remove the 2 slashes in "${!animal_name// }" and that worked for me.
If you are just trying to make sure the variable has some value, you can use defaults.
echo sudo chmod ...... ${animal_name:-doggo}
This will use doggo is animal_name is empty, but will leave it empty.
$: animal_name=
$: echo sudo chmod ...... ${animal_name:-doggo}
sudo chmod ...... doggo
$: echo "[$animal_name]" # still empty
[]
$: animal_name=bob
$: echo sudo chmod ...... ${animal_name:-doggo} # doesn't change is already set
sudo chmod ...... bob
If you want animal_name to ALWAYS default to doggo thereafter, use = instead of - and it will assign it as well if it's empty.
echo sudo chmod ...... ${animal_name:=doggo}
so:
$: animal_name=
$: echo sudo chmod ...... ${animal_name:=doggo}
sudo chmod ...... doggo
$: echo "[$animal_name]" # this time it was set
[doggo]
$: animal_name=bob
$: echo sudo chmod ...... ${animal_name:=doggo} # doesn't change if already set
sudo chmod ...... bob
Probably you mean indirection? This may help.
animal_name=""
doggo="I am doggo!"
if [[ -z "${animal_name}" ]]; then
animal_name="doggo"
fi
echo sudo chmod ...... ${!animal_name}
The ${!animal_name} reference the value of doggo, so the output is:
sudo chmod ...... I am doggo!
I am using the bash trap to make sure one function runs at any cost. I know trap is not specific to exitO or 1. Here is what I have done.
#!/bin/bash
set -e
#array to store server and deployed status
declare -A server_deployed
#path to file containing the server inventory
readonly filepath="/var/jenkins_home/workspace/server_list.txt"
#array to store to list of IPS
declare -A result #associative array
if [[ $TARGET == "ALL" ]]; then
while read line ; do
server_name=` echo $line | cut -d= -f1 `
result+=(["$server_name"]=${line#*=})
done < $filepath
else
singleserver=`cat $filepath | grep "$TARGET"`
server_name=`echo $singleserver| cut -d= -f1 ` # get the servername
serverip=`echo $singleserver| cut -d= -f2 ` # get tje server ip
result+=(["$server_name"]=$serverip) # gets the ip which is after equalto
fi
#function to send slack notification everytime
function sendMessage(){
for sd in "${!server_deployed[#]}"
do
echo "#########################################################"
echo "Sucecssfully deployed on $sd"
echo "#########################################################"
done
#let find the unsuccess list ,for which we need to find the array diff
for server_name in "${!result[#]}"
do
for sd in "${!server_deployed[#]}"
do
if [[ "$server_name" != "$sd" ]]; then
echo "Failed to deploy on $server_name"
fi
done
done
}
trap "sendMessage" INT EXIT
for server in "${!result[#]}"
do
upstream="MBM-TEST-ADMIN-BUILD"
#bundle filename
bundle="mbm_admin_dist"
name=$server
instance=${result[$name]}
#------copying the hash.php in build job to the deployed server home location
# ssh and move to desired location
sudo scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null /tmp/test/admin_hash.json ubuntu#$instance:/home/ubuntu/
mbmcms_workspace="/var/jenkins_home/workspace/$upstream"
cd $mbmcms_workspace
#remove if exist
if [ -e "$bundle.zip" ]
then
echo "Already Exist so Removing it First !!"
rm -f $bundle.zip
fi
#check if the dist folder exist that comes from successful build
if [ ! -d "dist" ]; then
echo "--------------------------------------------------------------"
echo "The dist folder does not exist, Please run BUILD job First !!"
echo "--------------------------------------------------------------"
exit 1
fi
#zip the file from the TEST & Build jobs
echo "starting to zip mbm-admin dist file created after test and build success!!"
zip --symlinks -x *.git* -r $bundle ./dist
#---------------------------------------------------------------
# copy development.php if non-production else copy production.php
# the file goes to the view/cms/
#---------------------------------------------------------------
sudo scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null development.php ubuntu#$instance:/home/ubuntu
sudo scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null production.php ubuntu#$instance:/home/ubuntu
#copy the bundle file to instance
scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -r $bundle.zip ubuntu#$instance:/home/ubuntu/
ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ubuntu#$instance '
SOURCE_FOLDER='/home/ubuntu/mbm-admin/dist/'
DESTINATION_FOLDER='/home/ubuntu/wpdata/plugins/manager/app/views/admin/admin_console/dist/'
rm -rf mbm-admin
mkdir -p mbm-admin
mv mbm_admin_dist.zip mbm-admin
cd mbm-admin
unzip mbm_admin_dist.zip
rm -f mbm_admin_dist.zip
sudo rsync -arz --force --delete --progress $SOURCE_FOLDER $DESTINATION_FOLDER
#moving the copied file to the /app/views/admin/admin_console
sudo mv /home/ubuntu/development.php /home/ubuntu/wpdata/plugins/manager/app/views/admin/admin_console
sudo mv /home/ubuntu/production.php /home/ubuntu/wpdata/plugins/manager/app/views/admin/admin_console
#moving the hash.php to the desired location
sudo cp -fv /home/ubuntu/admin_hash.json /home/ubuntu/wpdata/plugins/manager/app/views/admin/admin_console/hash.json
'
server_deployed+=(["$server"]="SUCCESS")
done
Here is the trap , as seen the script section
trap "sendMessage" INT EXIT
I need to run the sendMessage function whenever some exit code is
detected or the program exits due to any error.
Problem:
When I put the exit 1 at the end of the script the function gets called by the trap but suppose, If I put it somewhere in the middle or exactly after the main for loop starts the trap does not catch the exit code.
What am I not understanding or missing exactly in here?
I'm trying to write a provision script for Browscap, and I'm almost there, I just want to see what I'm doing wrong when trying to rewrite php.ini file.
The repo is here.
The provision script looks like this
#!/usr/bin/env bash
# Prettyfiers
BLUE='\033[0;36m'
NC='\033[0m' # No Color
DIR=`dirname $0`
echo "${BLUE}Setting up Browsecap${NC}"
# Check PHP version
PHP_VER=`php -r \#phpinfo\(\)\; | grep 'PHP Version' -m 1 | grep -Po -m 1 '(\d+\.\d+)' | head -1`
MIN_REQ="5.3"
if (( $(echo "${PHP_VER} < ${MIN_REQ}" |bc -l) )); then
echo "${BLUE}The PHP version is lower than 5.3 so browscap won't work. Please upgrade your PHP version to higher than 5.3${NC}"
exit 0
fi
echo "${BLUE}PHP version is${NC}" ${PHP_VER}
BROWSE_INI="/etc/php/${PHP_VER}/mods-available/php_browscap.ini"
# Check if browscap is already installed/set up
if [[ -f "${BROWSE_INI}" ]]; then
echo "${BLUE}Browscap is already installed${NC}"
else
# Set the browscap.ini and the php extension
touch "${BROWSE_INI}"
cp "php_browscap.ini" "${BROWSE_INI}"
echo "${BLUE}Browscap copied${NC}"
fi
PHP_INI="/etc/php/${PHP_VER}/fpm/php.ini"
# Check if php.ini exists before replacing
if [[ -f "${PHP_INI}" ]]; then
echo "${BLUE}php.ini exists${NC}"
# Check if the default value exists - by default it should be ;browscap = extra/browscap.ini
# If it doesn't then find browscap = and replace it with the correct one
if [ "$(grep -qe ";browscap" "${PHP_INI}")" ]; then
sudo sed -i "s|;browscap =|browscap = /etc/php/${PHP_VER}/mods-available/php_browscap.ini|g" "/etc/php/${PHP_VER}/fpm/php.ini"
else
sudo sed -i "s|browscap =|browscap = /etc/php/${PHP_VER}/mods-available/php_browscap.ini|g" "/etc/php/${PHP_VER}/fpm/php.ini"
fi
echo "${BLUE}php.ini changed${NC}"
else
echo "${BLUE}php.ini doesn't exist${NC}"
fi
When the provision ends and I check my php.ini I get
[browscap]
; http://php.net/browscap
;browscap = /etc/php/7.0/mods-available/php_browscap.ini /etc/php/7.0/mods-available/php_browscap.ini extra/browscap.ini
So I'm missing something in my sed command.
But what?
MVE
If you have VVV installed you can go to shh with vagrant ssh
Then go to /home/vagrant and create text.txt and test.sh
text.txt
[browscap]
;browscap = extra/browscap.ini
test.sh
#!/usr/bin/env bash
TEST_FILE="/home/vagrant/text.txt"
# Check if php.ini exists before replacing
if [[ -f "${TEST_FILE}" ]]; then
echo "text.txt exists"
# Check if the default value exists - by default it should be ;browscap = extra/browscap.ini
# If it doesn't then find browscap = and replace it with the correct one
if grep -q ";browscap" "${TEST_FILE}"; then
sudo sed -i "s|;browscap =|browscap = /etc/php/7.0/mods-available/php_browscap.ini|g" "${TEST_FILE}"
else
sudo sed -i "s|browscap =|browscap = /etc/php/7.0/mods-available/php_browscap.ini|g" "${TEST_FILE}"
fi
echo "text.txt changed"
else
echo "text.txt doesn't exist"
fi
This will result in text.txt
[browscap]
browscap = /etc/php/7.0/mods-available/php_browscap.ini extra/browscap.ini
Rewrite this statement
if [ "$(grep -qe ";browscap" "${PHP_INI}")" ]; then
to just
if grep -q ";browscap" "${PHP_INI}"; then
since you can directly use grep's return code in shell conditionals. The reason being in the former case, you are incorrectly checking the return code of grep to see if it succeeded, because the exit code is processed by the shell.
(or) alternatively you could also do
grep -qe ";browscap" "${PHP_INI}"
rc=$?
if [ $rc -eq 0 ]; then
echo 'match found'
fi
because grep returns a different exit code if its found something (zero) vs. if it hasn't found something (non-zero). In an if statement, a zero exit code is mapped to "true" and a non-zero exit code is mapped to false.
Also your sed statement should include the matching part after = which needs to be done as
sed -i "s|;browscap =.*|browscap = /etc/php/${PHP_VER}/mods-available/php_browscap.ini|g" "/etc/php/${PHP_VER}/fpm/php.ini"
Based on the MCVE you posted, you should replace this block of code:
if grep -q ";browscap" "${TEST_FILE}"; then
sudo sed -i "s|;browscap =|browscap = /etc/php/7.0/mods-available/php_browscap.ini|g" "${TEST_FILE}"
else
sudo sed -i "s|browscap =|browscap = /etc/php/7.0/mods-available/php_browscap.ini|g" "${TEST_FILE}"
fi
with just 1 line:
sudo sed -i 's|;?browscap =.*|browscap = /etc/php/7.0/mods-available/php_browscap.ini|' "${TEST_FILE}"
I'd like to use notify-send from within a bash script that is running in the background to inform the user about the progress of the script. More specifically this is a script that automagically runs when a USB flash drive is inserted and runs a scan with ClamAV.
Specifically at line 30 and line 66. So far, I'm not having any luck. Can someone give me some advice/help? Thanks.
#!/bin/bash
#doOnUSBinsert_0.2.sh
#Author : Totti
# Make it executable by running 'sudo chmod x doOnUSBinsert_0.2.sh'
if ! [ -f /etc/udev/rules.d/80-doOnUSBinsert.rules ]
then # rule not added
cp "$0" /usr/bin/doOnUSBinsert
chmod u x /usr/bin/doOnUSBinsert
# echo 'SUBSYSTEM=="usb", ACTION=="add", RUN ="/path/to/script.sh"' | sudo tee /etc/udev/rules.d/80-clamscan.rules
echo 'SUBSYSTEM=="usb", ACTION=="add", RUN ="/usr/bin/doOnUSBinsert & "' | tee /etc/udev/rules.d/80-doOnUSBinsert.rules
if [ $? -eq 0 ]
then
echo 'Rule Successfully added. See file "/usr/bin/doOnUSBinsert" if you wish to edit the command'
exit 0
else
echo 'ERROR while adding rule'
exit 1
fi
fi
lfile="/tmp/doOnUSBinsert.log" # udev
lfile2="/tmp/clamscanFromUdev.log" # clamscan
lfile3="/tmp/doOnUSBinsert_mount.log" # mount
notify-send "USB SCAN ON INSERT" "Currently scanning with ClamAV"
main ()
{
sleep 12 # let the partitions to mount
#cat /proc/$$/environ | tr '�' 'n' >> /tmp/udevEnvirn.txt
echo "found $ID_SERIAL" >> "$lfile"
cat /etc/mtab | grep "^$part_c" >> "$lfile.3"
if [ "$ID_SERIAL"x = 'x' ]
then
echo "Exiting on empty ID_SERIAL" >> "$lfile"
exit 1
fi
#Eg: ID_SERIAL --> /dev/disk/by-id/usb-sandisk....42343254343543
#i=0
echo 'searching partitions' >> "$lfile"
for partitionPath in $( find /dev/disk/by-id/ -name "*$ID_SERIAL*part*" )
do
echo "current partition = $partitionPath" >> "$lfile"
# part[i ]="$( readlink -f "$partition" )" # Eg Output: /dev/sdb1 , /dev/sdb2
part_c="$( readlink -f $partitionPath )"
mpoint="$( cat /etc/mtab | grep "^$part_c" | awk '{print $2}' )"
echo "partitionPath= $partitionPath, part = $part_c, mountpoint= $mpoint" >> "$lfile"
echo "Scaning --> $mpoint" >> "$lfile.2"
############################################
clamscan -r --bell "$mpoint"/* >> "$lfile.2"
#############################################
done
}
notify-send "USB SCAN ON INSERT" "Finished scanning with ClamAV"
main &
echo ______________________________________ >> "$lfile"
exit 0
I'm pretty new to the linux world, but while looking for a solution for a similar project I found THIS
Tip: An overview on the available icons can be found here. To send
desktop notification from a background script running as root (replace
X_user and X_userid with the user and userid running X respectively):
sudo -u X_user DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/X_userid/bus notify-send 'Hello world!' 'This is an example notification.'
Hope this will help others.
Depending on how you are running the script it may not have access to the display variable. Try running export DISPLAY=:0.0 prior to the command.
If you are running the script as a different user, ie root, then you may also need to run it as su - <logged in user> -c notify-send ... (I usually don't need to do this, but I remember having to at one point - but I cant recall which distro or version I was on at the time.)
I have the following problem. I need to create system-wide JDK_HOME and JAVA_HOME variables. First I want to create /etc/profile.d/java.sh and add
JDK_HOME to it. Then I want to append JAVA_HOME to this file. So far I have this code.
#!/bin/bash
create_env_var()
{
local varname="$1"
local varvalue="$2"
local filename="/etc/profile.d/$3"
if [ -e "$filename" ]; then
echo "**ERROR: file $filename already exists"
else
sh -c 'echo "$varname=$varvalue" > $filename'
chmod +x "$filename"
fi
}
append_env_var()
{
local varname="$1"
local varvalue="$2"
local filename="/etc/profile.d/$3"
if [ ! -e "$filename" ]; then
echo "**ERROR: file $filename not found"
else
sh -c 'echo "$varname=$varvalue" >> $filename'
chmod +x "$filename"
fi
}
create_env_var "JDK_HOME" "/usr/lib/jvm/java-7-openjdk-i386" "java.sh"
append_env_var "JAVA_HOME" "/usr/lib/jvm/java-7-openjdk-i386" "java.sh"
exit "$?"
However these lines don't work and I see the following errors:
sh: 1: cannot create : Directory nonexistent
chmod: cannot access ‘/etc/profile.d/java.sh’: No such file or directory
Would you please show me where everything goes wrong?
While you can remove the single quotes, there's no reason to create a subprocess and use sh -c.
change sh -c 'echo "$varname=$varvalue" > $filename'
to echo "$varname=$varvalue" > $filename
and sh -c 'echo "$varname=$varvalue" >> $filename'
to echo "$varname=$varvalue" >> $filename