`qdbus` command does not apply until scripts exits - linux

I have a script which I use to make it easier for me to connect to the many servers I need to SSH into. It's working well except that the terminal's title (Konsole tab title in my case) is being set to the name of my script, "() ./scripts/ssh". I updated the script and added a call to qdbus to set the Konsole tab title. It works, but only after the SSH session is closed / the script completes.
How do I make the qdbus command take affect immediately?
the script
#!/bin/bash
ENV=$1
HOST=$2
USER=${3:-my_username}
if [ -z ${ENV} ]; then
echo "First parameter must be the environment."
exit -1
fi
if [ -z ${HOST} ]; then
echo "Second parameter must be the host."
exit -1
fi
case "$ENV" in
# cases to determine proper hostname from abbreviated input
*)
echo "Unsupported environment: ${ENV}"
exit -1
esac
HOST="${HOST}.${ENV}.net"
# set tab title
qdbus >/dev/null "${KONSOLE_DBUS_SERVICE}" ${KONSOLE_DBUS_SESSION} setTabTitleFormat 0 "${USER}#${HOST}"
echo "Connecting to ${HOST} as ${USER} ..."
ssh ${USER}#${HOST}
# revert tab title -- COMMENTED OUT FOR TESTING
# qdbus >/dev/null "${KONSOLE_DBUS_SERVICE}" ${KONSOLE_DBUS_SESSION} setTabTitleFormat 0 "%w"
When I run my script ...
tab text is updated to () ./scripts/ssh
"Connecting" echo is displayed
I'm SSH'd in per usual
tab text is not updated
When I exit the SSH session, the tab text is set to "${USER}#${HOST}" as in the command above (before ssh).
I have added / comment out a line which reverts the tab text back to what it was before I ran the script (I think).

Related

How to reload profile files?

I am creating a script that I will put in /etc/profile.d/namescript.sh. What it does is to add time to the history command. The script is already done, but for my change to be executed I have to close the session.
I know the source command, and if I use it to reload the profiles outside the script it works, but if I put it inside the script it does not.
My code:
#!/bin/bash
FECHA_HORA="%d/%b/%Y %H:%M"
RUTA="/etc/profile.d"
PROOT="/etc/profile"
PUSER="$HOME/.profile"
if [[ ${UID} -ne 0 ]]; then
echo "Debes ejecutar el script con permisos de admistrador: sudo ${0}"
exit 1
fi
cat <<EOF> ${RUTA}/timeHistory.sh
export HISTTIMEFORMAT="${FECHA_HORA} "
EOF
exec bash "$PROOT" && exec bash "$PUSER"
exit 0
I have tried with exec and with source inside the script, and I can not get it to work, it only works when I close session. That is why I need to reload the profile files.

Get bash script to open terminal

In Windows when I double-click a Batch script, it will automatically open a terminal window and show me what's happening. If I were to double-click a bash script in Linux, a terminal window does not open to show me what is happening; it runs in the background. I have seen that one can use one script to launch another script in a new terminal window with x-terminal-emulator -e "./script.sh", but is there any bash command I can put into the same (one) script.sh so that it will open a terminal and show me what's happening (or if I need to answer y/n questions)?
You can do something similar to what Slax
developers do in their bootinst.sh:
#!/usr/bin/env sh
#
# If you see this file in a text editor instead of getting it executed,
# then it is missing executable permissions (chmod). You can try to set
# exec permissions for this file by using: chmod a+x bootinst.sh
#
# Scrolling down will reveal the actual code of this script.
#
# if we're running this from X, re-run the script in konsole or xterm
if [ "$DISPLAY" != "" ]; then
if [ "$1" != "--rex" -a "$2" != "--rex" ]; then
konsole --nofork -e /bin/sh $0 --rex 2>/dev/null || xterm -e /bin/sh $0 --rex 2>/dev/null || /bin/sh $0 --rex 2>/dev/null
exit
fi
fi
# put contents of your script here
echo hi
# do not close the terminal immediately, let user look at the results
echo "Press Enter..."
read junk
This script would run correctly both when started in graphical
environment and in tty. It tries to restart the script inside
konsole and xterm and but if it doesn't find neither of them it
will simply run in the background.

Run script in a new screen if true

I have a script where it will check if background_logging is true, if it is then I want the rest of the script to run in a new detached screen.
I have tried using this: exec screen -dmS "alt-logging" /bin/bash "$0";. This will sometimes create the screen, etc. but other times nothing will happen at all. When it does create a screen, it doesn't run the rest of the script file and when I try to resume the screen it says it's (Dead??).
Here is the entire script, I have added some comments to explain better what I want to do:
#!/bin/bash
# Configuration files
config='config.cfg'
source "$config"
# If this is true, run the rest of the script in a new screen.
# $background_logging comes from the configuration file declared above (config).
if [ $background_logging == "true" ]; then
exec screen -dmS "alt-logging" /bin/bash "$0";
fi
[ $# -eq 0 ] && { echo -e "\nERROR: You must specify an alt file!"; exit 1; }
# Logging script
y=0
while IFS='' read -r line || [[ -n "$line" ]]; do
cmd="screen -dmS alt$y bash -c 'exec $line;'"
eval $cmd
sleep $logging_speed
y=$(( $y + 1 ))
done < "$1"
Here are the contents of the configuration file:
# This is the speed at which alts will be logged, set to 0 for fast launch.
logging_speed=5
# This is to make a new screen in which the script will run.
background_logging=true
The purpose of this script is to loop through each line in a text file and execute the line as a command. It works perfectly fine when $background_logging is false so there are no issues with the while loop.
As described, it's not entirely possible. Specifically what is going on in your script: when you exec you replace your running script code with that of screen.
What you could do though is to start screen, figure out few details about it and redirect your console scripts in/output to it, but you won't be able to reparent your running script to the screen process as if started there. Something like for instance:
#!/bin/bash
# Use a temp file to pass cat's parent pid out of screen.
tempfile=$(tempfile)
screen -dmS 'alt-logging' /bin/bash -c "echo \$\$ > \"${tempfile}\" && /bin/cat"
# Wait to receive that information on the outside (it may not be available
# immediately).
while [[ -z "${child_cat_pid}" ]] ; do
child_cat_pid=$(cat "${tempfile}")
done
# point stdin/out/err of the current shell (rest of the script) to that cat
# child process
exec 0< /proc/${child_cat_pid}/fd/0
exec 1> /proc/${child_cat_pid}/fd/1
exec 2> /proc/${child_cat_pid}/fd/2
# Rest of the script
i=0
while true ; do
echo $((i++))
sleep 1
done
Far from perfect and rather messy. It could probably be helped by using a 3rd party tool like reptyr to grab console of the script from inside the screen. But cleaner/simpler yet would be to (when desired) start the code that should be executed in that screen session after it has been established.
That said. I'd actually suggest to take a step back and ask, what exactly is it that you're trying to achieve and why exactly would you like to run your script in screen. Are you planning to attach/detach to/from it? Because if running a long term process with a detached console is what you are after, nohup might be a bit simpler route to go.

Create SSH Connection Independent Of Calling Bash Script

I am trying to create a bash script that serves as a wrapper for numerous ssh connection options. Basically the user will run the script and the appropriate ssh command will then be created and executed based on their selections. I am trying to find a way to have the script exit and the ssh connection created, rather than having the script continue to run while the user is working on the remote server. Does anyone know if this is possible or how I could achieve this? Thanks!
Edit
Sorry, I should have posted my code:
display_main_menu(){
while true
do
clear
echo ""
echo " Select A Server:"
echo " -------------------------------"
echo " 1) Server 1"
echo " 2) Server 2"
echo " 3) Server 3"
echo " 4) Quit"
local selection
read -p " Enter choice [1 - 4] " selection
case $selection in
1)
# Open SSH Connection to Server 1
break
;;
2)
# Open SSH Connection to Server 2
break
;;
3)
# Open SSH Connection to Server 3
break
;;
4)
exit 0
break
;;
;;
*)
echo -e "Invalid Selection..." && sleep 2
;;
esac
done
}
Use:
exec ssh <pararameters>
The exec builtin command:
Synopsis
exec [-a NAME] [-cl] [COMMAND] [ARG...] [REDIRECTION...]
Description
The exec builtin command is used to
replace the shell with a given program (executing it, not as new
process)
set redirections for the program to execute or for the
current shell
If only redirections are given, the redirections affect the current shell without executing any program.

Adding a service startup script for Amazon linux AMI

I am using an Amazon Linux AMI and doing some custom modifications(added an axis2server, etc) on it and saving it as a new AMI. Now what I want to do is when the AMI boots up, start up axis2server(ie.axis2server should automatically start when the instance boots up). For that I used a init script like below and ran the following command:
chkconfig --add axisservice
But when I launch a new instance from my image, the axis2server is not getting started.
I just only need to execute the script /home/ec2-user/axis2-1.6.1/bin/axis2server.sh at startup. Am I missing anything here?
#! /bin/sh
# Basic support for IRIX style chkconfig
###
# chkconfig: 235 98 55
# description: Manages the services you are controlling with the chkconfig command
###
case "$1" in
start)
echo -n "Starting axisservice"
touch ~/temp.txt
cd /home/ec2-user/axis2-1.6.1/bin
./axis2server.sh &
echo "."
;;
stop)
echo -n "Stopping axisservice"
echo "."
;;
*)
echo "Usage: /sbin/service axisservice {start|stop}"
exit 1
esac
exit 0
I went through https://help.ubuntu.com/community/CloudInit as well and it provides a mechanism called User-Data Scripts, where a user can execute a script when launching the script.
$ euca-run-instances --key mykey --user-data-file myscript.sh ami-axxxx
This is a command line option and what I want is something like when I launch the instance through the UI, the script should be started.Therefore, I think the above option can not be used in my case. Please correct me if I am wrong.
Thanks,
H.
I bet the environment is not set(up correctly). This means that I am guessing that your shell script tries to start another program and it's not to be found.
So at first, I'd adjust the start part of your script (current):
echo -n "Starting axisservice"
touch ~/temp.txt
cd /home/ec2-user/axis2-1.6.1/bin
./axis2server.sh &
echo "."
Edited:
echo -n "Starting axisservice"
touch ~/temp.txt
cd /home/ec2-user/axis2-1.6.1/bin
./axis2server.sh
RETVAL=$?
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure
echo "."
So what did I do?
removed & so script waits for your shell script (axis2server.sh) to complete
checked the return status ($?) of your shell script
Further debugging:
Add set -x to your scripts to enable tracing and log both stderr and stdout.
Questions:
Are you are aware that stop (in your service script) doesn't do anything?
touch ~/temp.txt is that supposed to create /root/temp.txt? (I'm guessing root runs this script.)
If none of my suggestions work, can you share axis2server.sh and paste stderr and stdout?

Resources