Cannot get sed to update a string [duplicate] - unix

This question already has answers here:
Environment variable substitution in sed
(12 answers)
Closed 2 years ago.
It seems like sed is not replacing the string on my code.
What I intend for it to do is to change the property called "notification.enable" from false to true from server2 to activate, and, true to false in server1 to deactivate.
It works when I do it individually using below but when doesn't when being called from a function.
sed -i 's/notification.enable=false/notification.enable=true/g' /usr/config/activate.properties
function prompt_activate_server2_config {
activate="notification.enable=true"
deactivate="notification.enable=false"
dir=/usr/config
filename=$dir/activate.properties
output=$(grep "notification" $filename)
if [ -e $filename ];
then
sed -i 's/$deactivate/$activate/g' "$filename"
echo "Activated in Server 2"
echo $output;date
fi
}
function prompt_deactivate_server1_config {
activate="notification.enable=true"
deactivate="notification.enable=false"
dir=/usr/config
filename=$dir/activate.properties
output=$(grep "notification" $filename)
if [ -e $filename ];
then
sed -i 's/$activate/$deactivate/g' "$filename"
echo "Deactivated in Server 1"
echo $output;date
fi
}
I'm using function because I need to remotely execute the scripts from another server
So I call them using below. All the 'execute' stuff is on the above function. What am I missing?
if [ "$selection" == 'Activate Config' ]; then
#Activate server1/deactivate server2#
ssh user#server2 "$(typeset -f prompt_activate_server2_config); prompt_activate_server2_config"
sleep 2
ssh user#server1 "$(typeset -f prompt_deactivate_server1_config); prompt_deactivate_server1_config"
fi

You need to evaluate the two variables ($deactivate and $activate) and you do that by using double rather than single quotes:
sed -i "s/$deactivate/$activate/g" "$filename"
I would write it like this (and use sed rather than grep if you really need to print before/after):
update_config() {
local file=$1
local key=$2
local from=$3
local to=$4
[ -e "$file" ] && sed -i "s/\($key=\)$from/\\1$to/g" "$file"
}
update_config /usr/config/activate.properties 'notification\.enable' 'false' 'true'

Related

How to Run a Shell Command in a zsh-theme?

So, I have Oh My Zsh up and running, and I'm creating my own new zsh-theme. In it, I wish to grab the external IP address from https://api.myip.com - and I'm using curl & grep to grab it. Works fine when I enter it at the command prompt, but when embedded in my zsh-theme file it gives me an error:
zsh: no matches found: ((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5]).){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])
(23) Failed writing body
Jacobs-MacBook-Pro-2.local jacobjackson ttys002 0 [ ] 10/29/20 18:32:46 PM
Here is my zsh-theme:
PROMPT='%F{white}%M %n %y %j $(curl -s https://api.myip.com | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])') %F{green}%2c%F{blue} [%f '
RPROMPT='$(git_prompt_info) %F{blue}] %F{green}%W %* %F{yellow}%D{%p}%f'
ZSH_THEME_GIT_PROMPT_PREFIX="%F{yellow}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%f"
ZSH_THEME_GIT_PROMPT_DIRTY=" %F{red}*%f"
ZSH_THEME_GIT_PROMPT_CLEAN=""
And here is the command sequence that grabs the IP address:
curl -s https://api.myip.com | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
Try this:
# Function name that's compatible with
# http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#Prompt-Themes
# in case you ever want to build a full prompt theme.
# -s to prevent curl from outputting a progress bar.
# Use a service that simply outputs your IP, so you
# don't have to parse anything.
prompt_jacobjackson_precmd() {
psvar[1]=$( curl -s ifconfig.co )
}
# precmd hooks ru just before each new prompt.
autoload -Uz add-zsh-hook
add-zsh-hook precmd prompt_jacobjackson_precmd
# %1v inserts the 1st element of the psvar array. See
# http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Conditional-Substrings-in-Prompts
PS1='%1v > '
I decided to use some of Marlon Richert's ideas as well a few from the zsh-theme 'bureau.' :)
get_space () {
local STR=$1$2
local zero='%([BSUbfksu]|([FB]|){*})'
local LENGTH=${#${(S%%)STR//$~zero/}}
local SPACES=""
(( LENGTH = ${COLUMNS} - $LENGTH - 1))
for i in {0..$LENGTH}
do
SPACES="$SPACES "
done
echo $SPACES
}
_1LEFT="%F{white}$(curl -s https://api.myip.com | jq .ip -r) %F{green}\$(dirs -c; dirs)"
_1RIGHT="%F{yellow}%j jobs %F{cyan}\$(~/systemstatus.sh)"
actionjackson_precmd () {
_1SPACES=`get_space $_1LEFT $_1RIGHT`
#print
print -rP "$_1LEFT$_1SPACES$_1RIGHT"
}
setopt prompt_subst
PROMPT='%F{yellow}%n%F{white}#%F{green}%M $_LIBERTY%f '
RPROMPT='$(actionjackson_git_prompt) %F{green}%W %* %F{yellow}%D{%p}%f'
autoload -U add-zsh-hook
add-zsh-hook precmd actionjackson_precmd

Unexpected no such file error in zsh function

I have defined this function in zsh, but it cannot work on my computer.
function m() {
local path=/Users/james/Music/cloud_music_link
local cmd="ls $path | sed -n $1p"
echo `$cmd`
# afplay `$cmd`
}
It always said:
m:3: no such file or directory: ls /Users/james/Music/cloud_music_link | sed -n 10p
and when I copy the ls /Users/james/Music/cloud_music_link | sed -n 10p and run it in zsh, everything is ok, why would this happen?
And the folder cloud_music_link is a soft link, I am not sure if this matters.
You want to pass the file (or subdirectory) at a given position inside of your given directory first to echo, and then to aplay? Easily done, in a way compatible with both bash and zsh:
m() {
local num=${1:-1}
local dir=/Users/james/Music/cloud_music_link
local -a files=( "$dir"/* )
local file=${files[$(( num - 1 ))]}
echo "$file"
afplay "$file" &
}
See:
Why you shouldn't parse the output of ls
I'm trying to put a command in a variable, but complex cases always fail!
Finally I have figured it out, it is because the name of the variable path, I changed it to p and everything works OK. The name path will conflict with zsh.
This code works:
function m() {
local p=/Users/james/Music/cloud_music_link/
song="$(ls $p | sed -n $1p)"
echo $song
killall afplay
afplay "$p$song"&
}

Using WP_UnitTestCase scaffolding in PHPStrom with composer

I configured WP_UnitTestCase and the wp_cli and PHPUnit with composer in PHPStorm. I had an issue where it couldn’t find/use my WP DB username and password to create the DB so I created it manually in the terminal. (was this a mistake?) install-wp-tests.sh the installed, I was able to run some test did a bit of development and then shutdown my machine.
The next day, I started up my machine and attempted to continue where I left off. However PHPunit (should I be calling this WP_UnitTestCase instead?) Failed to run with the following errors.
Warning: require_once(/tmp/wordpress-tests-lib/includes/functions.php): failed to >open stream: No such file or directory in /thefullpathtowordpressprojectd/wp->content/plugins/myplugin/tests/bootstrap.php on line 8
Well /tmp/wordpress-tests-lib/ doesn’t exist
So I look into the install-wp-tests.sh and its installing itself to a tmp directory…okay?! (So ok I did notice that phpunit said Installing when I ran my tests the night before… so it reinstalls itself for every test!?)
Then I re-run ‘install-wp-tests.sh’, it fails when attempting to create the ‘wordpress-tests’ db since it already exist but I can now run tests again.
My question is even if the scaffolding/ WP_UnitTestCase reinstalls itself every time I run phpunit in the directory of my plugin folder where my phpunit.xml is. What do I have to change in the ‘install-wp-tests.sh’ or phpunit.xml so I don't have to manually reinstall for an existing project, how to clear the require_once error for the tmp empty directory?
Should I have to reinstall it everytime I reopen my project?
my install-we-test.sh is unchanged, but here it is:
#!/usr/bin/env bash
if [ $# -lt 3 ]; then
echo "usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version]"
exit 1
fi
DB_NAME=$1
DB_USER=$2
DB_PASS=$3
DB_HOST=${4-localhost}
WP_VERSION=${5-latest}
WP_TESTS_DIR=${WP_TESTS_DIR-/tmp/wordpress-tests-lib}
WP_CORE_DIR=${WP_CORE_DIR-/tmp/wordpress/}
set -ex
download() {
if [ `which curl` ]; then
curl -s "$1" > "$2";
elif [ `which wget` ]; then
wget -nv -O "$2" "$1"
fi
}
install_wp() {
if [ -d $WP_CORE_DIR ]; then
return;
fi
mkdir -p $WP_CORE_DIR
if [ $WP_VERSION == 'latest' ]; then
local ARCHIVE_NAME='latest'
else
local ARCHIVE_NAME="wordpress-$WP_VERSION"
fi
download https://wordpress.org/${ARCHIVE_NAME}.tar.gz /tmp/wordpress.tar.gz
tar --strip-components=1 -zxmf /tmp/wordpress.tar.gz -C $WP_CORE_DIR
download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php
}
install_test_suite() {
# portable in-place argument for both GNU sed and Mac OSX sed
if [[ $(uname -s) == 'Darwin' ]]; then
local ioption='-i .bak'
else
local ioption='-i'
fi
# set up testing suite if it doesn't yet exist
if [ ! -d $WP_TESTS_DIR ]; then
# set up testing suite
mkdir -p $WP_TESTS_DIR
svn co --quiet http://develop.svn.wordpress.org/trunk/tests/phpunit/includes/ $WP_TESTS_DIR/includes
fi
cd $WP_TESTS_DIR
if [ ! -f wp-tests-config.php ]; then
download https://develop.svn.wordpress.org/trunk/wp-tests-config-sample.php "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR':" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/yourusernamehere/$DB_USER/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/yourpasswordhere/$DB_PASS/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s|localhost|${DB_HOST}|" "$WP_TESTS_DIR"/wp-tests-config.php
fi
}
install_db() {
# parse DB_HOST for port or socket references
local PARTS=(${DB_HOST//\:/ })
local DB_HOSTNAME=${PARTS[0]};
local DB_SOCK_OR_PORT=${PARTS[1]};
local EXTRA=""
if ! [ -z $DB_HOSTNAME ] ; then
if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then
EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp"
elif ! [ -z $DB_SOCK_OR_PORT ] ; then
EXTRA=" --socket=$DB_SOCK_OR_PORT"
elif ! [ -z $DB_HOSTNAME ] ; then
EXTRA=" --host=$DB_HOSTNAME --protocol=tcp"
fi
fi
# create database
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
}
install_wp
install_test_suite
install_db
and my phpunit.xml
<phpunit
bootstrap="tests/bootstrap.php"
backupGlobals="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<testsuites>
<testsuite>
<directory prefix="test-" suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

How do I check if specific users are logged on with unix?

I try this
#!/bin/sh
until who | grep -E "$*"
do
sleep 60
done
echo "$* logged in"
but it works only with one user written in arguments. I need this shell program to work with multiple users that are written as arguments.
Iterate over $# and check the output of who for every given name:
#!/bin/bash
who="$(who)"; # Save the output of who
for user in "$#"; do # Iterate over $#
if echo "$who" | grep -q "$user"; then # Check if $user is in $who
echo "$user logged in";
fi;
done;
What were you trying to achieve with that loop? Do you want the script to wait until a user logs in?
The grep needs some work, because it does not limit the match to the first word on each line. Alternatively, filter the result from who. Here is a revised script:
#!/bin/sh
DONE=no
while [ $DONE = no ]
do
who="$(who | sed -e 's/[[:space:]].*//' |sort -u)"
for user in "$#"
do
for WHO in $who
do
if [ $WHO = $user ]
then
echo "$user logged in"
DONE=yes
break
fi
done
done
[ $DONE = no ] && sleep 60
done
As you can see, the grep is unnecessary.
Finally, change it to plain /bin/sh, because there is no need for a specific shell in this example.

Passing text to variable in KSH. Not Working

Hi I am struggling to solve this simple program. I am not able to pass the value from the text file to the variable.
I am stuck at this: value=$( sed -n "${line}p" rpt1.txt|awk {$3}
O/P:
1.sh[15]: test: argument expected
CODE:
wc `find /arbor/custom/gur/fold1`|grep -vi "total"| tee rpt1.txt
total1=`wc -l rpt1.txt`
wc `find /arbor/custom/gur/fold2`|grep -vi "total"| tee rpt2.txt
total2=`wc -l rpt2.txt`
line=1
if [ $line -le $total1 ]
then
value=$( sed -n "${line}p" rpt1.txt|awk {$3} )
if [ $value -eq 512 ];
then
sed -n "${line}p" rpt1.txt|awk '{print $4}'| tee direc.txt
fi
line =$line+1
else
echo "loop over"
fi
Shouldn't there be a print in front of $3 in the suspect line?

Resources