DEV Community

Gonçalo Morais
Gonçalo Morais

Posted on • Originally published at on

Run copied CLI commands with a leading “$” sign safer

I recently came across Stefan’s tip on how to run copied commands with a leading dollar sign and I thought it was a great idea! However, this heads-up caught my eye:

Use at your own risk. 🤓 Before implementing any functionality that makes running copied code easier, be aware that the internet’s a bad place. There’s always a chance that a command has malicious intent or even includes hidden commands.

This made me think: maybe I can build upon his example and add a small layer of protection, to prevent accidental errors when working a bit absentmindedly — we all do that from time to time.

Ask for confirmation before

Follow his tutorial and, when you get to the part when you’re writing the script, instead of simply executing the commands it gets, ask the user for explicit confirmation before proceeding. Use this as the content of your $ executable:

read -p "Are you sure you? [y/N]: " -n 1 -r
echo # move to a new line
if [[$REPLY =~ ^[Yy]$ ]]
    exec "$@"
Enter fullscreen mode Exit fullscreen mode

I used someone’s else suggestion in order to ask for confirmation, but this is a simple way of adding a small confirmation step. Anything that is not y or Y will skip the execution. This will hopefully help with the hidden commands issue Stefan made me aware of.

Top comments (0)