I want to execute a script portion after a successful ssh connection has been established. I'd like to make it easier for me to tail a log file with a script I am trying to write.

Here is the script work in progress:

echo "[Log Tunnel]" 
if [ "$1" == "foo" ] 
                echo "connecting to foo.dev.company.net" 
                ssh foo.dev.company.net        
                tail -f var/logs/staff/backend/backend.log # what's the way to do this
if [ "$1" == "bar" ] 
                echo "connecting to bar.dev.company.net" 
                ssh bar.dev.company.net         

When I run the script I expect the following:

[Log Tunnel]
connecting to foo.dev.company.net
me@foo.dev.company.net's password: ***********
# Output of Tail

I wonder if it is possible at all to have the ssh connection established and pass the subsequent shell a new script it should excecute right after startup.


My goal is to have a following tail to a log file on a remote server in my shell. The scrip should ease the way to tail those log files my simple typing ./rtail.sh foo.When executing that command I expect the shell to display the particular tail output depending on the remote server I've chosen by the shell argument. I just want a shortcut for:

  • ssh to remote server
  • tail -f path/to/logfile.log
  • 1
    Your question is not clear. Do you want to start an interactive ssh or do you want to run a specific command on the remote system? Do you want the tail command to run on the local or on the remote system? What current directory do you expect for the relative file path in the tail command? Please edit your question to add information, don't use comments for this purpose.
    – Bodo
    Jun 2, 2021 at 11:00
  • 1
    I agree the question is not clear. Something like this maybe? Jun 2, 2021 at 15:00
  • @Bodo editing done
    – xetra11
    Jun 2, 2021 at 21:54

1 Answer 1


If I understand correctly, you are looking for something like this:


echo "[Log Tunnel]" 
if [ "$1" = "foo" ] 
elif [ "$1" = "bar" ]

echo "connecting to $server" 
ssh "$server" tail -f "$file"
  • Can you elaborate how this is working? I just see a command after the ssh command. Is that all what's needed to "inject" a command into the subsequent remote shell?
    – xetra11
    Jun 2, 2021 at 22:01
  • @xetra11 You should read the man page of ssh. You don't need to "inject" a command into a running remote shell. ssh can be used for different purposes. Running a specified command or running an interactive shell are two possibilities.
    – Bodo
    Jun 2, 2021 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.