In a shell, I run following commands without problem,
ls -al
!ls
the second invocation to ls also list files with -al flag. However, when I put the above script to a bash script, complaints are thrown,
!ls, command not found.
how to realise the same effects in script?
You would need to turn on both command history and !-style history expansion in your script (both are off by default in non-interactive shells):
The expanded command is also echoed to standard error, just like in an interactive shell. You can prevent that by turning on the
histverifyshell option (shopt -s histverify), but in a non-interactive shell, that seems to make the history expansion a null-op.