-1

I am looking for a way to print the bash prompt, command and its output as shown below into an image for documentation purposes while studying, I wrote a quick command to do that, but I need the bash prompt to be automatically printed instead of me changing this part of the command [$USER@`hostname` ~]# when the user or path changes, not forgetting the tilde for home directory and #/$ depending on whether the user is root or not so that all I need to change is cmd="ls -l";, I also don't want to use $PWD because I get the complete path, rather I need exact bash prompt:

cmd="ls -l"; convert -font DejaVu-Sans-Mono-Book -pointsize 16 label:"$(echo "[$USER@`hostname` ~]# $cmd\n";$cmd)" /home/myuser/Desktop/result.png

The above results in this image, note that [root@centos7 ~] is also included in the image:

enter image description here

I tried the variable $PS1 from this answer and this answer, but I get:

[\u@\h \W]\$

Thank you

5
  • 1
    Possible duplicate of command to capture current command prompt text
    – muru
    Commented Aug 1, 2019 at 10:56
  • 1
    Though this might be more useful if you don't want an image: unix.stackexchange.com/questions/200637/…
    – muru
    Commented Aug 1, 2019 at 10:59
  • @elekgeek; the proposed duplicate's answer requires bash 4+; is that an option?
    – Jeff Schaller
    Commented Aug 1, 2019 at 18:30
  • Look @ my script, those options never worked for me on CentOS 7, this is why I posted here, coz the links proposed by you guys never worked for me and I have already read those threads before posting, anyway how do I find my bash version?
    – elekgeek
    Commented Aug 1, 2019 at 20:10
  • The purported dupe doesn't work with older versions of bash; there you could probably use ps1=$(PS1=$PS1 bash -i 2>&1 </dev/null); ps1=${ps1%exit}
    – user313992
    Commented Aug 2, 2019 at 4:15

1 Answer 1

0

I ended up writing a script because it seems there is no solution on the net:

#!/bin/bash

CMD=$1
#DIR=$(readlink -ve "/proc/$PPID/cwd")
DIR=`pwd`
PRIVILEGE='$'

#echo $DIR
[ $# -eq 0 -o $# -gt 1 ] && { echo -e "Usage:\n\t $0 command\n\t Command should be enclosed in quotations"; exit 1; }
if [ $UID -ne 0 ]; then echo "Please run this script with sudo:"; echo "sudo $0 $*"; exit 1; fi

mkdir -p /result

#echo $DIR
PATTERN="^\/home\/\w+$"
if [[ $DIR =~ $PATTERN || $DIR == '/root' ]]; then DIR='~'; else DIR=`basename $PWD`; fi
echo $DIR

if [ $UID -eq 0 ]; then PRIVILEGE='#'; fi
#echo $PRIVILEGE

NUM=`ls -vr /result/ | head -1 | sed -e 's/\..*$//'`
if [ ! -n "$NUM" ]; then NUM=1; else ((NUM++)); fi

convert -font DejaVu-Sans-Mono-Book -pointsize 16 label:"$(echo "[`id -u -n`@`hostname` $DIR]$PRIVILEGE $CMD";$CMD)" /result/$NUM.png
echo $NUM.png
1
  • if you like jeff, I you can delete this question, and I can add my answer to the older thread?
    – elekgeek
    Commented Aug 2, 2019 at 16:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .