scphantm
scphantm

Reputation: 4563

Make a Bash script echo executed commands

I put together a bunch of alias commands in a folder. Mainly ssh, so instead of having to type...

ssh [user]@[server]

...ten times a day, I can just type...

server

...and the alias script fires. The script is simply the command...

ssh [user]@[server]

This is all working fine, but I was wondering if there was a way in Bash where instead of firing the ssh command quietly, it would display the command that is being executed?

Upvotes: 71

Views: 52874

Answers (3)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137547

The existing answers answer the question in the title. But I'd like to address the underlying problem of more efficiently SSH-ing to a server.

Rather than create a bunch of bash script aliases, the arguably better way to do this is with an ssh_config file.

If you put this in ~/.ssh/config:

Host deadpool
    Hostname abcdefghijklmnop.my.verbose.hosting-service.com
    User scphantm
    # Lots of other useful options here

Then, rather than typing this:

$ ssh [email protected]

You can do this:

$ ssh deadpool

or

$ scp deadpool:/var/log/apache/access.log access_logs.txt

or

$ any_other_ssh-based_command deadpool

Config file reference:

Host Restricts the following declarations (up to the next Host keyword) to be only for those hosts that match one of the patterns given after the keyword.

HostName
Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts. The default is the name given on the command line. Numeric IP addresses are also permitted (both on the command line and in HostName specifications).

User
Specifies the user to log in as. This can be useful when a different user name is used on different machines. This saves the trouble of having to remember to give the user name on the command line.

Upvotes: 3

nooj
nooj

Reputation: 618

Put "-x" at the top of your script instead of on the command line:

File server

#!/bin/bash -x
ssh user@server

Execution

./server

results in:

+ ssh user@server
user@server's password: ^C

Upvotes: 20

Rob Hruska
Rob Hruska

Reputation: 120456

You can debug the script with -x, which will echo the commands and arguments.

bash -x script.sh

You can do this for specific portions of the file, too (from section 2.3.2 linked above):

set -x          # activate debugging from here
ssh [email protected] ...
set +x          # stop debugging from here

The output from -x might be a bit too verbose for what you're looking for, though, since it's meant for debugging (and not logging).

You might be better off just writing out your own echo statements - that'd give you full control over the output.

Upvotes: 92

Related Questions