title: In a bash read loop, processing ! (exclamation) and trapping CTRL-Z
body: <p>I am trying to extend bash with custom code that reuses bash's capability to terminate and suspend forked processes and also bash's expansion of !.</p>
  <p>I tried a variation of the code in <a href="https://stackoverflow.com/questions/12771909/bash-using-trap-ctrlc">BASH - using trap ctrl+c</a> that has certain lines commented out from that solution and a few lines added for trapping ctrlz:</p>
  <pre><code>#!/bin/bash
  # type &quot;finish&quot; to exit
  
  #stty -echoctl # hide ^C
  
  # function called by trap
  other_commands() {
      #printf &quot;\rSIGINT caught      &quot;
      #tput setaf 1
      #printf &quot;\rSIGINT caught      &quot;
      #tput sgr0
      #sleep 1
      #printf &quot;\rType a command &gt;&gt;&gt; &quot;
      echo &quot;&quot;
  }
  
  trap 'other_commands' SIGINT
  trap 'other_commands' TSTP
  trap 'other_commands' SIGTSTP
  
  #input=&quot;$@&quot;
  
  while true; do
      printf &quot;\rType a command &gt;&gt;&gt; &quot;
      read input
      [[ $input == finish ]] &amp;&amp; break
      bash -c &quot;$input&quot;
  done
  </code></pre>
  <p>CTRL C works nicely, it kills the created process but not the bash extension.</p>
  <p>However, CTRLZ kind of works.
  when I execute ls | more and then CTRLZ, it suspends the process:</p>
  <pre><code>dewan    1934441  0.0  0.1   9800  3144 pts/6    S+   17:00   0:00 bash ctrlc.sh
  dewan    1934442  0.0  0.1   9800  3300 pts/6    T+   17:00   0:00 bash -c ls | more
  </code></pre>
  <p>But I cannot do anything in the bash extension after that:</p>
  <pre><code>initx11
  j2h
  j2h.bat
  j2h.jar
  j2hlink
  jargipc
  --More--
  ^Z
  </code></pre>
  <hr />
  <p>I read here (<a href="https://stackoverflow.com/questions/20182454/shell-script-get-ctrlz-with-trap">Shell Script get CTRL+Z with Trap</a>) that sigstop cannot be trapped but sigtstp can (in case there is a difference), and as we see it is allowed by bash. Iwas wondering if there is a workaround. Uncommenting the lines from the original solution did not improve things.</p>
  <p>A second issue is that I cannot use ! to reuse history commands in the bash extension. For example, !! does not execute the last command.</p>
  <pre><code> jaroeold                     pt2t.sed                       uc
   jaroewithoutvt               r2b
  Type a command &gt;&gt;&gt; !ls
  bash: !ls: command not found
  Type a command &gt;&gt;&gt;
  </code></pre>
  <p>The ! prefix is not expanded by bash. Is there a way to make bash expand it? I can  duplicate the functionality but was curious if one can devise a solution that did not require such duplication.</p>
  <p>Thanks, and this my first stackoverflow question I believe so pardon any mistakes in formatting and contents.</p>