Bash script to change a string in /etc folder?
I am wanting to create a script to change one of the values for the authorization file. (See Article TS3287 in the KB)
I assumed that I could use the sed command to do this, but I am getting an error when attempting to run. Any ideas?
Below is the code I wrote ...
#!/bin/bash
OLD="<string>The owner or any administrator can unlock the screensaver.</string>"
NEW="<string>(Use SecurityAgent.) The owner or any administrator can unlock the screensaver.</string>"
DPATH="/etc/authorization"
BPATH="/etc"
TFILE="/tmp/out.tmp.$$"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
if [ -f $f -a -r $f ]; then
/bin/cp -f $f $BPATH
sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f"
else
echo "Error: Cannot read $f"
fi
done
/bin/rm $TFILE
You do the testing- this script should work->
#!/bin/bash
#This script needs to run as root
ROOT_UID=0
if [[ $UID -ne $ROOT_UID ]]; then
echo "YOU MUST BE ROOT TO RUN THIS SCRIPT"
exit 1
fi
OLD="<string>The owner or any administrator can unlock the screensaver.<\/string>"
NEW="<string>(Use SecurityAgent.) The owner or any administrator can unlock the screensaver.<\/string>"
cp /private/etc/authorization /tmp/auth.tmp
sed "s/$OLD/$NEW/" /tmp/auth.tmp > /tmp/authorization
mv /private/etc/authorization /private/etc/authorization.previous
mv /tmp/authorization /private/etc/authorization
rm /tmp/auth.tmp
Similar Messages
-
hello!
i want to write a bash script for my wireless lan. for this i need the information, if the network daemon has connected successfully or failed.
but there is a big problem: starting network success' every time, whether there was an error or not:
$ /etc/rc.d/network start
:: Starting network profile: 00wlan_home [BUSY]
Error for wireless request "Set Mode" (8B06) :
SET failed on device wlan0 ; No such device.
[FAIL]
:: Starting Network [DONE]
$ ls /var/run/daemons/
... network ...
can someone help me please? how can i realize that "::Starting Network ..." also fails and the script returns an exit status 1?
thanks for your help, maybe we can improve the script. but i'm not a geek in bash!
mfg iggyiggy wrote:
hello!
i want to write a bash script for my wireless lan. for this i need the information, if the network daemon has connected successfully or failed.
but there is a big problem: starting network success' every time, whether there was an error or not:
$ /etc/rc.d/network start
:: Starting network profile: 00wlan_home [BUSY]
Error for wireless request "Set Mode" (8B06) :
SET failed on device wlan0 ; No such device.
[FAIL]
:: Starting Network [DONE]
$ ls /var/run/daemons/
... network ...
can someone help me please? how can i realize that "::Starting Network ..." also fails and the script returns an exit status 1?
thanks for your help, maybe we can improve the script. but i'm not a geek in bash!
mfg iggy
try using netcfg to start the wireless profile, that should keep you happy until the new network scripts are unleashed... which won't have this problem.
James -
New to bash scripting; making script to change laptop CPU governor
I've got an old laptop and I like to be able to change the governor between performance and ondemand depending on whether or not I've got the laptop plugged in. I'd really like to be able to do this from a shortcut on the desktop, so I decided to try making a bash script that used Zenity dialogs to accomplish this.
I think it turned out pretty much how I'd like, however the error handling on getting the root password authenticated is pretty broken. I'm not sure how exactly I should go about it.. I think that the long timeout that occurs when you enter a wrong password for su is causing problems. Is there a better way of doing this? I don't use sudo, and I'd really prefer to avoid it and stick to using su if at all possible.
#!/bin/bash
#This script will supply a Zenity dialog with the option to change the laptop's governor.
#It will use a Zenity dialog to acquire the root password from user for autorization to change the governor.
#Set up some variables we will use.
optionPerformance="FALSE"
optionOndemand="FALSE"
#Read the current state of the governor.
currentGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
#Change the variables we previously set up to reflect current state of governor. This will be used to determine which option is pre-selected in the Zenity dialog we will create.
if [ $currentGovernor = 'performance' ]
then optionPerformance="TRUE"
fi
if [ $currentGovernor = 'ondemand' ]
then opitonOndemand="TRUE"
fi
#Set up Zenity dialog which allows user to select the governor they want active. The currently active governor will be selected by default.
#User's input will go to the wantedGovernor variable for future use.
wantedGovernor=$(zenity --list --text "Select which governor you want to make active:" --radiolist --column "" --column "Options" $optionPerformance "performance" $optionOndemand "ondemand")
#Check to see if user clicked Cancel button.
if [ $? = 1 ]
then exit 0
fi
#Did user select the already active profile? If so, simply report that and exit.
if [ $wantedGovernor = $currentGovernor ]
then
newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
zenity --info --text "Governor is already set to $newGovernor.\n\nNo changes were made."
exit 0
fi
#Now that we know what the user wants, let's do it.
#We will use cpupower to change the governor. This will require root privileges, so we will use Zenity to get the root password from user and pipe it into su. (Is this the best way?)
zenity --title "Password for root:" --password | su -c "cpupower frequency-set -g $wantedGovernor"
#Check to see if user clicked Cancel button.
if [ ${PIPESTATUS[0]} = 1 ]
then exit 0
fi
#Check to see if user entered incorrect root password.
if [ ${PIPESTATUS[1]} = 1 ]
then
zenity --error --text "Incorrect root password.";
exit 1
fi
#Now that we've made the change, let's check the current state of the governor again so that we can report it to the user and they can verify success.
newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
zenity --info --text "Governor is now set to $newGovernor."
Last edited by gilmoreja (2015-01-26 21:49:19)Thanks for the advice, Awebb. I looked into gksu but I didn't like how it offered to save the root password in gnome-keyring. I found an alternative, ktsuss, and decided to go with that instead.
I'll post the finished script here, for anyone who is ever interested in such a thing:
#!/bin/bash
#This script will supply a Zenity dialog with the option to change the laptop's governor.
#It will use a Zenity dialog to acquire the root password from user for autorization to change the governor.
#Set up some variables we will use.
optionPerformance="FALSE"
optionOndemand="FALSE"
#Read the current state of the governor.
currentGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
#Change the variables we previously set up to reflect current state of governor. This will be used to determine which option is pre-selected in the Zenity dialog we will create.
if [ $currentGovernor = 'performance' ]
then
optionPerformance="TRUE"
fi
if [ $currentGovernor = 'ondemand' ]
then optionOndemand="TRUE"
fi
#Set up Zenity dialog which allows user to select the governor they want active. The currently active governor will be selected by default.
#User's input will go to the wantedGovernor variable for future use.
wantedGovernor=$(zenity --list --text "Select which governor you want to make active:" --radiolist --column "" --column "Options" $optionPerformance "performance" $optionOndemand "ondemand")
#Check to see if user clicked Cancel button.
if [ $? = 1 ]
then exit 0
fi
#Did user select the already active profile? If so, simply report that and exit.
if [ $wantedGovernor = $currentGovernor ]
then
newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
zenity --info --text "Governor is already set to $newGovernor.\n\nNo changes were made."
exit 0
fi
#Now that we know what the user wants, let's do it.
#We will use cpupower to change the governor. This will require root privileges, so we will use ktsuss to get that.
ktsuss cpupower frequency-set -g $wantedGovernor
#Now that we've made the change, let's check the current state of the governor again so that we can report it to the user and they can verify success.
newGovernor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
zenity --info --text "Governor is now set to $newGovernor." -
What do you think of my Bash Script? What about the error checking?
Well what do you think of this Bash script
It works
I gave it some problems (i.e. unpluged the ethernet, messed up the URL's, uninstaled some programs...) to see if would report errors and stop or just keep going... But it did
I just kind of thought up a way to do some error checking with the commands that I know.....
What is a better way to do error checking?
What do you think I should add/Do to this script?
#!/bin/bash
# Shell script to make a USB Tumb Drive for Flashing BIOS on a Lenovo Ideapad Y510.
# This script needs to be owned and run as ROOT with the "sudo command"
# i.e. sudo usbbiosflasher
# If you have anyideas send me a PM on ubuntufourms.org my user name is HunterThomson
# Name/Rename this script usbbiosflasher and save it to the ~/home directory.
# Then run the command- chown root:root usbbiosflasher
# Then run the command- chmod 755 usbbiosflasher
# Then copy the script to the directory /usr/bin.
# Run this comand to do that- sudo cp ~/usbbiosflasher /usr/bin
# You also must have the program "mbr" installed
# You can install the mbr program by running this comand in the shell on Ubuntu
# sudo apt-get install mbr
# In Arch Linux you have to get it from Aur
# First you will need to know a few things...
# You will also need to know the Mount Point i.e. /media/disk and the /dev path i.e. /dev/sdb1.
# You can find these by using the df -T comand.
# Run df -T in the shell. Then plug in the USB Thumb Drive and run the df -T comand agin.
# The new listing is the USB Thumb Dirve.
# Also check to make sure the File System tipe is vFAT or FAT16 or FAT32.
# If it is not use gparted to format it to FAT32.
# I am farly certen that all USB Thumb drives come formated with FAT file system out of the BOX.
# You may want to fromat it anyway just to make sure.
echo "Interactive Shell Script to Make a USB Thumb Drive \for Flashing BIOS On a Lenovo Ideapad Y510"
echo ""
echo "You will need to have the program mbr installed"
echo "If you are on Ubuntu Linux you can retreve it form the repositories"
echo "If you are on Arch Linux you will need to get it from the Aur repository"
echo "Open anuther shell and \do that now..."
echo ""
verify="n"
while [ "$verify" != y ]
do
printf "Do you have mbr installed... yes or no?"
read AN1
echo ""
printf "You answered... $AN1 I have installed mbr. Is this correct... y or n?"
read verify
done
echo ""
if [ "$AN1" == "no" ]
then
echo "Install mbr now. Then run this script agin"
exit
else
echo "contunuing script"
fi
echo ""
# The next comand will make a directory to put needed files into. Note this file and everything init will be owned by root.
mkdir ~/usbbiosfiles && check1="yes"
if [ "$check1" = "yes" ]
then
echo "Made directory usbbiosfiles... OK"
else
echo "Could not \make directory usbbiosfiles"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
exit
fi
# The next two comands will get the FreeDOS file and the .ROM file.
cd ~/usbbiosfiles && checka="yes"
if [ "$checka" = "yes" ]
then
echo "Changing to the usbbiosfiles directory... OK"
else
echo "Could not Change to the usbbiosfiles directory"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
wget "http://www.fdos.org/bootdisks/autogen/FDOEM.144.gz" && check2="yes"
if [ "$check2" = "yes" ]
then
echo "Download of FreeDOS... OK"
else
echo "Could not Download FreeDOS"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
wget "http://ubuntuforums.org/attachment.php?attachmentid=78460&d=1216648756" && check3="yes"
if [ "$check3" = "yes" ]
then
echo "Download of the BIOS.ROM \file... OK"
else
echo "Could not Downlad the BIOS.ROM \file"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
# The next comand will name the .ROM file to the right name.
mv ~/usbbiosfiles/attachment.php?attachmentid=78460\&d=1216648756 ~/usbbiosfiles/06CN29WW.bios.update.tar.bz2 && check4="yes"
if [ "$check4" = "yes" ]
then
echo "Renameing of the BIOS.ROM \file... OK"
else
echo "Could not rename the BIOS.ROM \file"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
echo ""
# The next two comands set the variables. DEVX for the path i.e. /dev/xxx and MOUNTX for the mount point i.e. /media/xxx
verify="n"
while [ "$verify" != y ]
do
echo "You will need to know the Mount Point and the dev Path. You will also need to \make sure the File System \type is vFAT, FAT16 or FAT32."
echo ""
echo "With the USB Thumb Drive unpluged, Open another shell and run the comand df -T Then plug \in the USB Thumb Drive and run the comand df -T one \more time. The new device listed is the USB Thumb Drive. Note the Mount Point and The dev Path and the File system Type i.e. vFAT... If the File System \type is not vFAT, FAT16 or FAT32 you will need to fromat it with gparted. You may want to format the USB Thumb Drive anyway just to \make sure. In any \case delete all files and directorys on the USB drive before you go any ferther with this program."
echo ""
printf "Enter the dev path the USB Thumb Drive is at?"
read DEVX
echo ""
echo "Are you sure $DEVX is the dev path of the USB Thumb Drive... y or n?"
read verify
done
echo ""
verify="n"
while [ "$verify" != y ]
do
printf "What is the Mount Point of the USB Thumb Drive?"
read MOUNTX
echo ""
echo "Are you sure $MOUNTX is the Mount Point of the USB Drive... y or n?"
read verify
done
echo ""
install-mbr --enable A1 --partition 1 --force --timeout 0 $DEVX && check5="yes"
if [ "$check5" = "yes" ]
then
echo "Installing MBR on USB Thumb Dirve... OK"
else
echo "Could not install MBR on USB Thumb Drive"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
tar xjf ~/usbbiosfiles/*.tar.bz2 && check7="yes"
if [ "$check7" = "yes" ]
then
echo "Unpacking BIOS.ROM file... OK"
else
echo "Could not unpack BIOS.ROM file"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
gunzip ~/usbbiosfiles/FDOEM.144.gz && check8="yes"
if [ "$check8" = "yes" ]
then
echo "Unpacking FreeDOS files... OK"
else
echo "Could not unpack FreeDOS files"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
mkdir ~/usbbiosfiles/fdoem144 && check9="yes"
if [ "$check9" = "yes" ]
then
echo "Made directory fdoem144 in direcoty usbbiosfiles... OK"
echo ""
echo "Going to \sleep \for 5secs"
else
echo "Could not make directory fdoem144 in usbbiosfiles directory"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
modprobe loop && sleep 5 && check0="yes"
if [ "$check0" = "yes" ]
then
echo "Modprobeing loop... OK"
else
echo "Could not \modprobe loop"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
mount -o loop ~/usbbiosfiles/FDOEM.144 ~/usbbiosfiles/fdoem144 && check10="yes"
if [ "$check10" = "yes" ]
then
echo "Mounting FreeDOS on the fdoem144 directory... OK"
else
echo "Could not \mount FreeDOS on the fdoem144 directory"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
cp ~/usbbiosfiles/fdoem144/* $MOUNTX && check11="yes"
if [ "$check11" = "yes" ]
then
echo "Copying FreeDOS files to $MOUNTX... OK"
else
echo "Could not copy FreeDOS files to $MOUNTX"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
cp ~/usbbiosfiles/*.ROM $MOUNTX && check12="yes"
if [ "$check12" = "yes" ]
then
echo "Copying BIOS.ROM files to $MOUNTX... OK"
else
echo "Could not copy BIOS.ROM files to $MOUNTX"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
sync && check13="yes"
if [ "$check13" = "yes" ]
then
echo "Runing the syncing command... OK"
else
echo "Could not run the syncing command"
echo "look above \for \info"
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this scrip agin"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
rm -r ~/usbbiosfiles
exit
fi
umount ~/usbbiosfiles/fdoem144 && check14="yes"
if [ "$check14" = "yes" ]
then
echo "Unmounting of FreeDOS... OK"
else
echo "Could not unmount FreeDOS"
echo "Look above for errors or problems reported and fix the problem"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this script agin"
rm -r ~/usbbiosfiles
exit
fi
verify="n"
while [ "$verify" != y ]
do
printf "Do you see any errors... yes or no?"
read AN2
echo ""
printf "You answered... $AN2 to errors. Is this correct... y or n?"
read verify
done
echo ""
if [ "$AN2" == "yes" ]
then
echo "User Repoted... Error"
echo "Look above for errors or problems reported and fix the problem"
echo ""
echo "removeing directory usbbiosfiles..."
echo ""
echo "Reformat the USB Stick to FAT32 with gparted"
echo "Fix the problem and run this script agin"
rm -r ~/usbbiosfiles
exit
else
echo "Success"
echo "I did a lot of error checking too and didnt find anything"
echo ""
echo "Go get a pen and paper to write down these instructions"
printf "Then hit the Enter to continue"
read WAIT
echo ""
echo "Now leave the USB Thumb Drive pluged into your computer and Reboot. When the Lenovo Logo POST screen appears hit F2 to enter the CMOS setup utility. Go over to BOOT tab and go down to HardDrive \(Not Boot Order) \then \select the USB Thumb Drive as the 1st hard drve. Then F10 and yes to save changes. Your compter will reboot agin. Then when the Lenovo Logo POST Screen appers on reboot hit F4 to enter the BIOS FLASHING program. The USB Thumb Drive will be seen as the C drive \in the list on the Left, Select it. Then \select the .ROM \file \in the list on the Right and start the BIOS FLASH. \(NOTE Your hart may stop beating... This is normal) Pray to any God you know of and your computer should restart just like normal. Hit F2 and the BIOS will now stay it is 06CN29WW. You will need to \set the boot order to the way you like it and other things \if you need to because they have been changed to the default."
fi
echo ""
echo "End of script"
Last edited by hunterthomson (2008-08-10 11:17:47)Personally..... (this is just how I would have written it - if it works, then it's good enough for me though )
I would change this whole block:
verify="n"
while [ "$verify" != y ]
do
printf "Do you have mbr installed... yes or no?"
read AN1
echo ""
printf "You answered... $AN1 I have installed mbr. Is this correct... y or n?"
read verify
done
echo ""
if [ "$AN1" == "no" ]
then
echo "Install mbr now. Then run this script agin"
exit
else
echo "contunuing script"
fi
To this much shorter code:
MBR='/usr/bin/install-mbr' # Or where ever you expect it to be
if [ ! -x $MBR ] ; then
echo "mbr doesn't appear to be installed."
echo "If it is installed, check it's location, make sure it's executable and then make sure the MBR variable in this script is correct"
exit 1
fi
I wouldn't have used the checkXX variables for each stage:
mkdir ~/usbbiosfiles
if [ $? != 0 ] ; then
#failed
echo "Could not \make directory usbbiosfiles"
echo "look above \for \info"
echo "Fix the problem and run this scrip agin"
exit 1
else
echo "Made directory usbbiosfiles... OK"
fi
There is an issue with the way you do your verifications - the user can never get out unless they answer 'y' or hit CTRL+C. Something like this gives them options:
verify="n"
while [ "$verify" != "y" && "$verify" != "n" ]; do
echo "You need to answer 'y'es or 'n'o"
read verify
echo $verify | tr "[:upper:]" "[:lower:]" # This converts the answer to lowercase so replies entered in upper case will still work
done
if [ $verify != 'y' ] ; then
exit 1
fi
One last thing I try to do in scripts... Declare all your binaries as variables at the start of the program, then execute the binary program by using the variable. For example:
# Binaries
TAR='/bin/tar'
CP='/bin/cp'
CHMOD='/bin/chmod'
# Execute tar and chmod the created file
$TAR cvzf /tmp/tarfile.tar.gz /etc/*.conf
$CHMOD 400 /etc/*.conf
This way, it's easy to change the path in future without having to hunt through the script if the paths change, and it also ensures you're calling the programs using the full paths to make sure you're not executing some strange variant or alias that someone has setup. If I use `chmod` 30 times in a script, and the path changes in the future or on a different system (`chmod` is a bad example cause it's highly unlikely to change, but you know what I mean), then all you need to do is update the variable at the start of the script, and it all works again without having to script-hunt and change it 30 times. -
???? how to launch bash script in cron ????
with help from people in this forum, I successfully debugged the syntax in a shell script I wrote (my syntactical faux pas had to do with sending a multi-line mail message from a bash script).
I can manually launch my script from Terminal's command line, and it works perfectly (well, at least it does exactly what I told it to do:). I try to launch it via cron, and it doesn't appear to ever launch.
In /var/cron/tabs/root, the pertinent line of text reads:
00 22 * * * /usr/local/customShellScripts/script.sh
so it is supposed to launch daily at 10PM.
Other jobs listed in /var/cron/tabs/root do run, because I get emails to my postfix admin account saying that they do. However, none of those other jobs are shell scripts; they are stuff like:
24 06 * * 5 /usr/sbin/diskutil verifyVolume /
The directory listing for /var/cron/tabs/root reads:
$ ls /var/cron/tabs
total 4
drwxr-xr-x 3 root wheel 102 Mar 25 18:53:28 2006 .
drwxr-xr-x 3 root wheel 102 Mar 20 17:13:47 2005 ..
-rw-r--r-- 1 root wheel 1040 Mar 31 20:28:10 2006 root
The directory listing for script.sh reads:
$ ls /usr/local/customShellScripts/
total 24
drwxr-xr-x 6 root wheel 204 Mar 31 18:31:27 2006 .
drwxr-xr-x 11 root wheel 374 Mar 5 12:26:23 2006 ..
-rw-r--r-- 1 root wheel 6148 Feb 4 14:13:22 2006 .DS_Store
-rwxr-xr-x 1 root wheel 8058 Mar 31 20:27:50 2006 script.sh
for debug, the first two lines of script.sh read:
#!/bin/sh
/usr/bin/touch /foo
but the file /foo never gets created. I tried using just "touch /foo" and that didn't work either.
Also, since the script has a lot of calls to "echo," "expr," "date," "cut," "awk," etc., if I ever get cron to execute the script past the shebang line, do I have to preface all those calls with their full path? Or can I do something like in the old /etc/crontab file, where they defined a path variable up front
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
and the script will be smart enough to look in those directories for the appropriate executables?
But, getting back to the first problem, I am obviously overlooking something very basic, which is not surprising since I'm self-taught (and I guess, Apple Unix Discussions forum taught) at this unix thing and shell scripting. So, can anybody bail me out here...again?
2001 Quicksilver G4 Mac OS X (10.4.5)Hey Reese
You bailed me out, dude! Apparently, my difficulties stemmed from me trying to directly edit /var/cron/tabs/root with pico. Never seemed to bother the other stuff, but it did this time. I am totally inept with vi, the default editor for crontab -e, which is why I had cheated before, and directly edited the /var/cron/tabs/root, el.al., so I had to find out how to
export EDITOR='pico'
in my .bashrc
After having done that, no problem, except for a latent programming logic bug that has reared its ugly head (my script is doing some date manipulation with today's and yesterday's date, and my script crashed and burned on the month change and with stuff related to single-digit date sequence numbers <10).
But, hey, I learned how to reset my default editor, so as to make life easier for me when it comes time to dorking with crontab files, and I learned that when the crontab file says "DO NOT EDIT THIS FILE - edit the master and reinstall," it means it!
Thanx for the troubleshooting hint. -
Get initial directories in bash script
I have a variable TEST in a bash script
TEST=/ABCService/ZeroComposite/deploy/sca_XYZ.jar
I want to parse this TEST variable to have a new variable COMPOSITE_DIR with value "/ABCService/ZeroComposite". Looks pretty simple but I am on it for about 3 hours now. Exhausted all option with regex, dirname, basename etc. There has to be a simple way to do this.
ThanksGiving up after only 3 hours already?
How about the following:
var=$(echo $TEST | rev | cut -d'/' -f3- | rev)
echo $var
/ABCService/ZeroComposite
The cut command allows to specify a character delimiter that acts like a field separator. The parameter -f3- would normally extract the string starting at field number 3 and all remaining fields. The trick is to reverse the order of the string so that the cut command will cut from the end to the beginning, instead from the beginning to the end, and then reverse the string again to get the result. -
Simple bash scripting help needed..
I want to learn som simple bash scripting in order to automate various tasks.. Im totally noob, so bear with me
First of all I would like to set configs without using nano.. is there a simple command for this? For example if i want change my hostname in /etc/rc.conf.. how can i print the current vallue and how can i change it`?
i was thinking something like this to get the current value:
# cat /etc/rc.conf | grep HOSTNAME=
which returns HOSTNAME="myhostname"
how can i change this value with one or more commands whitout touching the rest of the file?abesto wrote:
A slightly naive solution:
CHOICE="lisa"
NAMES="homer marge lisa bart maggie"
if [ "`echo \" $NAMES \" | grep \" $CHOICE \"`" ]; then
echo "this is how you do it"
fi
The extra spaces inside the escaped quotes are to ensure that only a whole word is "matched".
You can also replace the elif's with a loop through a list of "the other variables". Then you'd use the loop variable instead of $CHOICE above.
grep can check on word-bounderies with \< and \>, or with the -w switch. The -q switch suppresses any messages and exits with exit-code 0 when the first match is found:
if echo "${NAMES}" | grep -qw "${CHOICE}"; then
Nice and readable, should work, but i haven't tested it
EDIT:
Procyon wrote:CHOICE="lisa"
NAMES="homer marge lisa bart maggie"
if [[ $NAMES =~ $CHOICE ]]; then echo match; fi
This one also matches elisa, ie. no check on word bounderies. You should be carefull with that
Last edited by klixon (2009-04-23 09:40:22) -
[SOLVED] XMMS2 media hotkeys, bash scripts
Hi!
For the really beginners of the XMMS2 users as me, should be a nice something like a guide/tutorial.
Here is the bash scripts that might enchant functionality and be more useful for use of the media keys.
For randomizing before any other action you can use even something like:
xmms2 playlist shuffle ; xmms2 jump 1; xmms2 play
# Just for dummies
The Preview hotkey loop.
From the begin of the playlist to the end of it when current is the first one being played:
#!/bin/bash
#Play the previews or first if end of the playlist
if [ "XX"$(xmms2 prev | awk '{print $1}') == "XXServer" ] ; then
if [ "XX"$(xmms2 jump $(xmms2 list | grep -i '/' |wc -l) | awk '{print $1}') == "XXServer" ] ; then
xmms2 playlist list;
echo The playlist is empty, please choose one from of the above ;
echo or add a new songs to the playlist with a '"xmms2 add"';
fi; fi;
#It takes time to count to the last song in the playlist, longer it is more time it takes :(. I haven't found a better way yet.
The Next hotkey loop.
When the end of the playlist is reached then goto jumping to the first one song in the playlist:
#!/bin/bash
#Play the first song if in the end of the playlist
if [ "XX"$(xmms2 next | awk '{print $1}') == "XXServer" ] ; then
if [ "XX"$(xmms2 jump 1 | awk '{print $1}') == "XXServer" ] ; then
xmms2 playlist list;
echo The playlist is empty, please choose one from of the above ;
echo or add a new songs to the playlist with a '"xmms2 add"';
fi; fi;
For the Play/Pause key:
#!/bin/bash
#For the single Play/Pause key
GetStatus=$(xmms2 current | awk -F":" '{print $1}')
#Any command line parameters to the script for randomizing of the playslist.
if [ "S" != "S"$1 ] ; then
xmms2 playlist shuffle
fi;
if [ "$GetStatus" == "Playing" ]; then xmms2 pause;fi
if [ "$GetStatus" == "Paused" ]; then xmms2 play;fi
if [ "$GetStatus" == "Stopped" ]; then
xmms2 play
GetStatus=$(xmms2 current | awk -F":" '{print $1}')
if [ "$GetStatus" == "Stopped" ]; then
xmms2 playlist list;
echo The playlist is empty, please choose one from of the above ;
echo or add a new songs to the playlist with a '"xmms2 add"';
fi
fi
or you can use even xmms2 toggle command line for the play/pause hotkey.
Turn On/Off repeat/loop of the playlist:
#!/bin/bash
GetStatus=$(xmms2 server config playlist.repeat_all )
case $GetStatus in
"playlist.repeat_all = 1") xmms2 server config playlist.repeat_all 0 ; sudo beep; echo is OFF ;;
"playlist.repeat_all = 0") xmms2 server config playlist.repeat_all 1 ; sudo beep ; sudo beep ; echo is ON;;
esac
You can install beep but the beep has a problem, you can run it only as a root but a more danger way is to by pass this by adding the beep into /etc/sudoers , e.g. yourusername ALL=NOPASSWD: /usr/sbin/beep. Be careful! It may expose your system for unwanted access to and do a harm. The best way is to find a better way for notification of changes.
If someone has another script solutions for the multimedia hotkeys or media fun for XMMS2 then please share with us!
Automation is power of the shell
Notice
The hotkey names of my Digital Media Keyboard 3000, but I think that it becomes more as a standard, it is just to get a faster access to the names.
XF86AudioPlay, XF86AudioNext, XF86AudioPrev,XF86AudioStop
XF86AudioMute (amixer -c 0 set Master toggle), *, (pactl set-sink-mute 0 toggle)
XF86AudioRaiseVolume (amixer -c 0 set Master 3+), xmms2 server volume +3, (pactl set-sink-volume 0 +3%)
XF86AudioLowerVolume (amixer -c 0 set Master 3-). xmms2 server volume -3, (pactl set-sink-volume 0 -- -3%)
amixer = ALSA
pactl = PulseAudio (0 is index of the sinks, you can see which you can use with pacmd list-sinks, marked with * is default)
The other way to increase and decrease volumes is here.
Change between ALSA and PulseAudio sound servers for XMMS2
nyxmms2 server config output.plugin pulse
nyxmms2 server config output.plugin alsa
Otherwise you can use xev to retrieve the names of the supported keys by X server, as I know X server has a limitations to the 255 key numbers/keycodes. One more but less useful for GUI is showkey, just to know that it is also and always exists, with a great manual about the kbd keys.
* To mute/unmute XMMS2 you can use xmms2 server volume 0 / xmms2 server volume 100 or for more advanced e.g. xmms2 server volume -c left 100/xmms2 server volume -c right 100 and combine with any keys you wish the way is best for you. I haven't found any way to make anything to remember status after mute/unmute of xmms2. Alias for the mute only is xmms2 mute. If you will find it before me please help .
Here is one more guide for the BlackBox menu. I could not get xmms2 mlib loadall to work in Arch.
In Arch you must use xmms2 playlist sort instead of xmms2 sort because it doesn't work otherwise.
xmms2 playlist sort album
xmms2 playlist sort title
xmms2 playlist sort artis
Last edited by Andy_Crowd (2014-10-18 11:34:45)Zariel wrote:
i guess something like this?
%optical ALL=(ALL) NOPASSWD: ALL
I found the clues for this in the sudoers manual:
handy ALL = NOPASSWD: /sbin/umount /CDROM,\
/sbin/mount -o nosuid\,nodev /dev/cd0a /CDROM
Which works in so far as now mounting no longer needs the password.
Which leaves me with the problem of trying to understand how to get Worker to mount the optical drive on command.
If I enter the bash command in the Terminal as follows:
mount /mnt/dvd
the media is mounted, after which I can push the button in Worker, which I have configured with:
/mnt/dvd
& the root list of the optical media is displayed in the active panel of Worker.
I just haven't been able to get Worker to use "mount /mnt/dvd" yet, there will be a way, I wonder how long it will take me to find it? lol
Last edited by handy (2008-11-19 06:48:09) -
[SOLVED] Bash scripts to mount & unmount optical drive in Worker?
I'm running XFCE on Arch with the HAL daemon being called in /etc/rc.conf.
I can access media on my optical drive (DVD's or CD's) through the desktop icon that appears after HAL has recognised the drive, VLC automatically does its thing as does NeroLinux.
The reason I'm posting is that I found a great DOpus clone yesterday called Worker - http://www.boomerangsworld.de/cms/worker/index?lang=en, which I am in the process of configuring.
A problem I have is being able to access the optical drive via Worker.
The way it is on my system, with HAL handling it, the first line (see below) appears after HAL mounts the media, which basically makes the two lines below it useless:
/media/<title of disk>
/media/cd
/media/dvd
I have tried configuring Worker to use /media/dvd (or cd), to access the optical media, these don't work for the reason stated above, & /dev/sd0 doesn't work either.
So, do I have to turn off HAL, uncomment the lines in fstab & use mount?
A little bash script, that would do the job for me would be great, as Worker will accept a script or a command string.
I am a bash baby, so if someone can see a solution please post it?
All input welcome.
Thanks.
Last edited by handy (2008-11-19 04:11:02)Zariel wrote:
i guess something like this?
%optical ALL=(ALL) NOPASSWD: ALL
I found the clues for this in the sudoers manual:
handy ALL = NOPASSWD: /sbin/umount /CDROM,\
/sbin/mount -o nosuid\,nodev /dev/cd0a /CDROM
Which works in so far as now mounting no longer needs the password.
Which leaves me with the problem of trying to understand how to get Worker to mount the optical drive on command.
If I enter the bash command in the Terminal as follows:
mount /mnt/dvd
the media is mounted, after which I can push the button in Worker, which I have configured with:
/mnt/dvd
& the root list of the optical media is displayed in the active panel of Worker.
I just haven't been able to get Worker to use "mount /mnt/dvd" yet, there will be a way, I wonder how long it will take me to find it? lol
Last edited by handy (2008-11-19 06:48:09) -
Sending email using bash script
Hello:
I am working on writing a bash script to notify one or more users by email of certain events. Run from the Terminal command line, and having the script "echo" text of (what would be) a form letter with in-line variable expansion (i.e., ${VARIABLE}), all seems to work as anticipated. Eventually, I want cron to launch this shell script, and send an email to an "on-subnet" user (I have postfix enabled on my Mac, and there are multiple local user accounts).
I found some stuff on the web about sending mail from bash scripts, and so I made a small little test script, that reads like this:
#!/bin/bash
VARIABLE[1]="The 12,345 quick brown foxes "
VARIABLE[2]="jumped over the 67,890 lazy dogs."
mail -s "a test email" jv << EOF
This is a test:
${VARIABLE[1]}
${VARIABLE[2]}
This is the last line of the test message.
EOF
echo "script completed"
It worked... almost... It sent a local email to my postfix mail account that read like this:
This is a test:
The 12,345 quick brown foxes
jumped over the 67,890 lazy dogs.
This is the last line of the test message.
EOF
echo "script completed"
So, I have two questions. First, the easy one (I hope):
How do I delimit the end of the text, that I want to be the message body of the email, from portions of the script that follow said email text?
Next question is a little more involved. You know how, in Mail.app, if you go to Mail Preferences>Accounts>Account Information, you can put multiple email addresses, comma-delimited, in the "Email Address" field? So, if a person entered "[email protected], [email protected], [email protected]" in this field, then, even though (s)he may be at home, and using their home ISP's mail server, (s)he could send an email apparently from either their home, work, or school email address. Of course, the mail headers clearly would show it came from and through their home machine and home ISP, but it would be displayed in the recipient's Mail client viewer as having come from one of [email protected], [email protected], or [email protected].
I'd like to do something similar here, whereby the email (that is being sent to one or more local users' postfix account on my computer) would apparently be sent from "watchdog@localhost" rather than from "jv@localhost" like it seems to do by default. Whatever account the script is run from (or presumbably, whose cron tab is launching the script) is what the "From" address is set to.
I'd rather not create an additional mail account, because I am using Mac OS X built-in accounts for the postfix mailboxes (I don't want to have to maintain a plaintext username:password file in postfix, and I don't want to create an additional user account on the computer).
So, is there a way to specify an alternate "From" username when invoking the mail -s ${SUBJECT} ${RECIPIENT} command in a bash script? Or is there a different, alternate mail command that will let me do so? (please include a description of syntax and how I'd package the above message text for the alternate method).
Thanks in advance, all!Hi j.v.,
The > after EOF is just a typo (or may be added by the Discussion ?) and you must delete it; other > are prompts from the interactive shell. Andy's post shows an interactive use of shell, not a shell script (note the shell prompt % in front of the commands). A typical use of here document may look like
command <<ENDOFDATA
ENDOFDATA
There must be no spaces before and after ENDOFDATA. The word ENDOFDATA can be EOF or any other string which is guaranteed not to appear in the text (the .... in the example above).
You can modify the From: header by using sendmail command (postfix has it as a compatibility interface):
/usr/sbin/sendmail -t <<EndOfMessage
Subject: test mail
To: jv
From: watchdog
This is a test:
${VARIABLE[1]}
${VARIABLE[2]}
This is the last line of the test message.
EndOfMessage
There must be a blank line between the headers and the mail body.
I assume that you send these mails only to users on your local Mac. Please do not send mails to remote users by using the sendmail command unless you know what you are doing completely.
PowerMac G4 Mac OS X (10.4.5) -
[SOLVED] problem with spaces and ls command in bash script
I am going mad with a bash script I am trying to finish. The ls command is driving me mad with spaces in path names. This is the portion of my script that is giving me trouble:
HOMEDIR="/home/panos/Web Site"
for file in $(find "$HOMEDIR" -type f)
do
if [ "$(dateDiff -d $(ls -lh "$file" | awk '{ print $6 }') "$(date +%F)")" -gt 30 ];
then echo -e "File $file is $(dateDiff -d $(ls -lh "$file" | awk '{ print $6 }') "$(date +%F)") old\r" >> /home/panos/scripts/temp;
fi
done
The dateDiff() function is defined earlier and the script works fine when I change the HOMEDIR variable to a path where there are no spaces in directory and file names. I have isolated the problem to the ls command, so a simpler code sample that also doesn't work correctly with path names with spaces is this:
#!/bin/bash
HOMEDIR="/home/panos/test dir"
for file in $(find "$HOMEDIR" -type f)
do
ls -lh "$file"
done
TIA
Last edited by panosk (2009-11-08 21:55:31)oops, brain fart. *flushes with embarrassment*
-- Edit --
BTW, for this kind of thing, I usually do something like:
find "$HOMEDIR" -type f | while read file ; do something with "$file" ; done
Or put those in an array:
IFS=$'\n' ; files=($(find "$HOMEDIR" -type f)) ; unset IFS
for file in "${files[@]}" ; do something with "$file" ; done
The later method is useful when elements of "${files[@]}" will be used multiple times across the script.
Last edited by lolilolicon (2009-11-09 08:13:07) -
Can't get conky-cli and bash scripts to both display in dwm statusbar!
I'm trying to configure my dwm status bar to display some simple information using conky-cli and bash scripts. At first I tried just letting conky run the bash scripts (for network and volume state), but this increased my cpu usage by about 5%, which is significant considering I normally have 1-3% usage when idle. Also, I wanted to keep conky because it makes the display of certain information easy, such as cpu & RAM usage.
The problem is I'm having trouble getting both to display side by side. Here are the relevant parts of my .xinitrc:
network(){
iwconfig wlan0 2>&1 | grep -q no\ wireless\ extensions\. && {
echo wired
exit 0
essid=`iwconfig wlan0 | awk -F '"' '/ESSID/ {print $2}'`
stngth=`iwconfig wlan0 | awk -F '=' '/Quality/ {print $2}' | cut -d '/' -f 1`
bars=`expr $stngth / 10`
case $bars in
0) bar='[-------]' ;;
1) bar='[#------]' ;;
2) bar='[##-----]' ;;
3) bar='[###----]' ;;
4) bar='[####---]' ;;
5) bar='[#####--]' ;;
6) bar='[######-]' ;;
7) bar='[#######]' ;;
*) bar='[--!!!--]' ;;
esac
echo $essid$bar
exit 0
volume(){
vol=$(amixer get Master | awk -F'[]%[]' '/%/ {if ($7 == "off") { print "MM" } else { print $2 }}' | head -n 1)
echo Vol: $vol%
exit 0
conky | while true; read line; do xsetroot -name "`$line` `volume` `network` `date '+%a %m-%d-%Y %I:%M%p'`"; done &
exec dwm
(let me know if it would help to post any other files)
For some reason when I run this I only get the network/volume scripts and date running, updating every second (I think). The conky line just doesn't show up. I don't know what could be wrong, since I didn't see any error messages.
An even better solution would be to just have shell scripts to display CPU and MEM usage. I have a dual-core cpu, cpu0 and cpu1. I'd like to see both percentages if possible, or at least a percentage that is an accurate average of the two or something. In conky-cli I have something that shows:
cpu0/1: xx% xx%
Also, seeing RAM usage would help a lot. In conky it shows:
mem: xx% (xxxMB)
These are the ways I would like to have bash scripts show them, if possible, but I have zero skill in bash programming. I made this an option in case it's easier/cleaner/less resource hungry than a conky solution. Personally, if they're about the same in these aspects, I would prefer something with conky and the shell scripts because conky is so extensible, yet it's only flaw is executing scripts with minimal resource usage.
Help?Thanks. I was thinking of using load average to save a few characters, but I didn't quite understand the numbers. I'll try that once I get to my Linux box, but could you please explain or post a link to something that explains load average (what's low, high, normal, etc.)?
EDIT: I found a website that explains loadavg. I now have my dwm status bar displaying it perfectly (yay!). Now I just need to add a few more things like battery status, etc. and I might be done. I'll probably post here if I have more questions, though.
Thanks for your help!
Last edited by Allamgir (2009-07-18 14:41:11) -
I have been searching high and low for this one. I have a vbscript that can successfully perform the function if one file is listed. It does a Wscript.echo on the results and if I run this via command using cscript, I can output to a text file
that way. However, I cannot seem to get it to work properly if I want it to search ALL the files in the folder. At one point, I was able to have it create the output file and appear as if it worked, but it never showed any results when the script
was executed and folder was scanned. So I am going back to the drawing board and starting from the beginning.
I also have a txt file that contains the list of string text entries I would like it to search for. Just for testing, I placed 4 lines of sample text and one single matching text in various target files and nothing comes back. The current script
I use for each file has been executed with a few hundred string text lines I want it to search against to well over one thousand. It might take awhile, but it works every time. The purpose is to let this run against various log files in a folder and
let it search. There is no deleting, moving, changing of either the target folder/files to run against, nor of the file that contains the strings to search for. It is a search (read) only function, going thru the entire contents of the folder and
when done, performs the loop function and onto the next file to repeat the process until all files are searched. When completed, instead of running a cscript to execute the script and outputting the results to text, I am trying to create that as part
of the overall script. Saving yet another step for me to do.
My current script is set to append to the same results file and will echo [name of file I am searching]: No errors found. Otherwise, the
output shows the filename and the string text that matched. Because the results append to it, I can only run the script against each file separately or create individual output names. I would rather not do that if I could include it all in one.
This would also free me from babysitting it and running each file script separately upon the other's completion. I can continue with my job and come back later and view the completed report all in one. So
if I could perform this on an entire folder, then I would want the entries to include the filename, the line number that the match occurred on in that file and the string text that was matched (each occurrence). I don't want the entire line to be listed
where the error was, just the match itself.
Example: (In the event this doesn't display correctly below, each match, it's corresponding filename and line number all go together on the same line. It somehow posted the example jumbled when I listed it)
File1.txt Line 54
Job terminated unexpectedly
File1.txt Line 58 Process not completed
File1.txt
Line 101 User input not provided
File1.txt
Line 105 Process not completed
File2.txt
No errors found
File3.txt
Line 35 No tape media found
File3.txt
Line 156 Bad surface media
File3.txt Line 188
Process terminated
Those are just random fake examples for this post.
This allows me to perform analysis on a set of files for various projects I am doing. Later on, when the entire search is completed, I can go back to the results file and look and see what files had items I wish to follow up on. Therefore, the
line number that each match was found on will allow me to see the big picture of what was going on when the entry was logged.
I actually import the results file into a spreadsheet, where further information is stored regarding each individual text string I am using. Very useful.
If you know how I can successfully achieve this in one script, please share. I have seen plenty of posts out there where people have requested all different aspects of it, but I have yet to see it all put together in one and work successfully.
Thanks for helping.I'm sorry. I was so consumed in locating the issue that I completely overlooked posting what exactly I was needing help with. I did have one created, but I came across one that seemed more organized than what I originally created. Later
on I would learn that I had an error in log location on my original script and therefore thought it wasn't working properly. Now that I am thinking that I am pretty close to achieving what I want with this one, I am just going to stick with it.
However, I could still use help on it. I am not sure what I did not set correctly or perhaps overlooking as a typing error that my very last line of this throws an "Expected Statement" error. If I end with End, then it still gives same
results.
So to give credit where I located this:
http://vbscriptwmi.uw.hu/ch12lev1sec7.html
I then adjusted it for what I was doing.
What this does does is it searches thru log files in a directory you specify when prompted. It looks for words that are contained in another file; objFile2, and outputs the results of all matching words in each of those log files to another file: errors.log
Once all files are scanned to the end, the objects are closed and then a message is echoed letting you know (whether there errors found or not), so you know the script has been completed.
What I had hoped to achieve was an output to the errors.log (when matches were found) the file name, the line number that match was located on in that file and what was the actual string text (not the whole line) that matched. That way, I can go directly
to each instance for particular events if further analysis is needed later on.
So I could use help on what statement should I be closing this with. What event, events or error did I overlook that I keep getting prompted for that. Any help would be appreciated.
Option Explicit
'Prompt user for the log file they want to search
Dim varLogPath
varLogPath = InputBox("Enter the complete path of the logs folder.")
'Create filesystem object
Dim oFSO
Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")
'Creates the output file that will contain errors found during search
Dim oTSOut
Set oTSOut = oFSO.CreateTextFile("c:\Scripts\errors.log")
'Loop through each file in the folder
Dim oFile, varFoundNone
VarFoundNone = True
For Each oFile In oFSO.GetFolder(varLogPath).Files
'Verifies files scanned are log files
If LCase(Right(oFile.Name,3)) = "log" Then
'Open the log file
Dim oTS
oTS = oFSO.OpenTextFile(oFile.Path)
'Sets the file log that contains error list to look for
Dim oFile2
Set oFile2 = oFSO.OpenTextFile("c:\Scripts\livescan\lserrors.txt", ForReading)
'Begin reading each line of the textstream
Dim varLine
Do Until oTS.AtEndOfStream
varLine = oTS.ReadLine
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
Dim colMatches, strName, strText
Do Until oErrors.AtEndOfStream
strName = oFile2.ReadLine
objRegEx.Pattern = ".{0,}" & strName & ".{0,}\n"
Set colMatches = objRegEx.Execute(varLine)
If colMatches.Count > 0 Then
For Each strMatch in colMatches
strText = strText & strMatch.Value
WScript.Echo "Errors found."
oTSOut.WriteLine oFile.Name, varLine.Line, varLine
VarFoundNone = False
Next
End If
Loop
oTS.Close
oFile2.Close
oTSOut.Close
Exit Do
If VarFoundNone = True Then
WScript.Echo "No errors found."
Else
WScript.Echo "Errors found. Check logfile for more info."
End If
End if -
Using Bash script to edit config file
This is a really simple question, but given that I'm just learning Bash scripting and having this solved now would be really illustrative for me, I would really thank some help here.
I'm using uzbl, and running Tor+Polipo. So, as you will see below in the tail of the config file, there is a line to redirect the requests of uzbl through Polipo.
# === Post-load misc commands ================================================
sync_spawn_exec @scripts_dir/load_cookies.sh
sync_spawn_exec @scripts_dir/load_cookies.sh @data_home/uzbl/session-cookies.txt
# Set the "home" page.
#set uri = https://duckduckgo.com
# Local polipo proxy
set proxy_url = http://127.0.0.1:8123
# vim: set fdm=syntax:
What I want to accomplish is to comment in/out that line with a key shortcut on Awesome. I've thought of doing 2 scripts to do so and using 2 differente key shortcuts, but I want to "toggle" the proxy redirection with only 1 shortcut. To do so, I suppose that the script should go something like:
if
tool 'set proxy_url = http://127.0.0.1:8123' config_file
then
tool '#set proxy_url = http://127.0.0.1:8123' config_file
else
if
tool '#set proxy_url = http://127.0.0.1:8123' config_file
then
tool 'set proxy_url = http://127.0.0.1:8123' config_file
fi
fi
I know little about sed, but I think is the tool for this job. The most intriging part to me is to ask sed to print the regular expression when it finds it in the config file, and use that as an input in the conditional statement.
Well, this is a mess I have done here. Hope there is a simple answer to this.
Thanks in advance.-You can do this with a single sed command:
sed -i 's/^#set proxy_url/set proxy_url/;
t end;
s/^set proxy_url/#set proxy_url/;
: end' config_file
This edits the file in-place (-i) and first tries to replace the commented with the uncommented line. If that suceeds, sed jumps to the "end" label. If not, it tries to replace the uncommented with the commented line. Thus you don't have to include any logic about the current state: if the first substitution succeeds, the line was obviously commented, if not, it was uncommented, and the second substitution should succeed.
Note that my knowledge of sed is very limited. There might be a simpler way to do this.
EDIT: For the sake of example, here's how to do the same in bash using regular expressions. Note how this script needs to use a temporary file to simulate in-place editing, how it needs to process the file line by line manually, etc. All things that sed does out of the box...
#!/bin/bash
tmp=test.conf.tmp
echo -n "" > "$tmp"
while read line; do
if [[ "$line" =~ ^#set\ proxy ]]; then
echo "${line/\#/}" >> "$tmp"
elif [[ "$line" =~ ^set\ proxy ]]; then
echo "#$line" >> "$tmp"
else
echo "$line" >> "$tmp"
fi
done < test.conf
mv test.conf.tmp test.conf
To answer your original question, the line
if [[ "$line" =~ ^#set\ proxy ]]; then
reads: if the line begins with a "#", followed by "set proxy", then...
Last edited by hbekel (2011-03-20 10:40:16) -
HOW DO I RUN A UNIX BASH SCRIPT FROM JAVA??
HI. Here's a tricky little problem i have. There's a unix bash script that has some commands in it, that manipulate a file. It appends a certain string variable to a file called users. The users file is an ordinary text file.
I know this script to work perfectly, when i invoke it like this directyl from the command line: ./addusers.sh
or even: bash /downloads/selinux/policy/addusers.sh
Now, i have a java program, and its meant to just execute that script. It doesnt throw any Exceptions at runtime. But when i look at the users file, and expect it to have an extra line that was the string variable, the file is UNTOUCHED!
Again, direct command line invocation works, but not from java. Here's what my invocation from java looks like:
Process p = Runtime.getRunTime().exec("bash downloads/selinux/policy/addusers.sh");
The strange thing is, i tried a different bash command. I tried:
Process p = Runtime.getRunTime().exec("mkdir /temporary");
and this worked!
so why not the other one??
I cant figure it out.You say:
bash /downloads/selinux/policy/addusers.sh
And you say in Java:
Process p = Runtime.getRunTime().exec("bash
downloads/selinux/policy/addusers.sh");
As if a leading / would be missing from the Java
version...nyix says:>
...OK sorry about that. i DO have a / in front of the downloads.... section in the java method. So its:
Process p = Runtime.getRunTime().
exec("bash /downloads/selinux/policy/addusers.sh");
HELP please?
Maybe you are looking for
-
I already purchased the cable for the mini DVI port, the DVI to video and s-video cable. It works well, but i was wondering what can exacty do with this cable, i already connected it to a tv and duplicate the image so i can see everything i do on a t
-
Despite my Javascript for Firefox 23 being "enabled" ( I checked re the "about:config" steps), some websites are still asking me to enable my Javascript to view content. Safari works without any problem. OS/X 10.8.4
-
Hi I am sending a data from R/3 to XI using abap proxy. Here if the data packets are waiting in the queue for some time am getting an error " Time Limit Exceeded" and user is cancelling the job for processing in R/3 pls advice me how do i find the qu
-
What do i have to do to follow bloggers on mozilla firefox
Is it ok to have my blogs I following in my bookmarks pages or is there an easier place to put them, and how do I put them there!!!!
-
How to select a row in Grid? no a cell
Clict the grid, I want to select a whole row, not a cell and that the Cell of Grid is readonly how to do? thanks