Sanzhar Dan Sanzhar Dan - 4 months ago 15
Linux Question

How to create own Linux console app?

To be more specific, I want to know how to create console apps that I can execute directly from shell with all parameters and functions that can be applied with it.

There're tons of these apps, such as composer, laravel, mongo, node, meteor and many more.

Answer

Any program can be a console application. As mentioned by Alex, argv and argv can be used to read in the command line arguments. From there its just a regular program that does something.

A very simple example in bash script

#!/bin/bash

# download.sh

echo "Downloading $1 and saving it to $2"
cd $2
wget $1
echo "Finished downloading"

This takes two arguments (bash reads arguments as $n, where n is an integer starting at 0)

$ bash download.sh www.example.com/logo.png ~/Pictures/
  Downloading www.example.com/logo.png and saving it to /home/user/Pictures
  Finished downloading

In other languages, you use argv (argument vector) and argc (argument count).

A simple python script

#!/bin/python

# hello.py

from sys import argv

name = argv[1]
if name == 'bob':
    print('hello', name)

The most important thing to realize is that a program doesn't really care if its getting input from command line or from a GUI. The only thing that changes is how the user interacts with the program. If you wish to learn more, a search phrase such as 'SOME_LANGUAGE getting user input' or 'SOME_LANGUAGE getting command line arguments/input' will provide a lot of examples and documentation, where SOME_LANGUAGE is the language you want to use.

Comments