『神器点滴之Emacs』用emacs编写shell script?

都说Emacs是万能的,但从没想到emacs居然可以作为脚本语言来编写linux系统shell script。对于熟悉linux shell编程的同学来说。这也许是开始eLisp世界的一个更好的入口。。。


下面的例子示范了shell script中最常用的几个任务:

1. 读取命令行参数

2. 遍历命令行参数

3. 输出到stdout

4. 输出到stderr

5. 执行外部命令

6. 获取外部命令输出


hello.el

#!/usr/local/bin/emacs --script

;; find your emacs with : "which emacs" and set to the first line

(princ "This is message to stdout\n")

(message "This is err message to stderr")

(setq args command-line-args)

(princ (format "\nread command line with variable : %s\n" args))

(princ "\nenum arguments with car\n")

(setq i 0)

(while (setq arg (car args))

(princ (format "arg[%d] = %s\n" i arg))

(setq args (cdr args))

(setq i (1+ i)))

(princ "\nenum arguments with nth\n")

(setq args command-line-args)

(setq i 0)

(while (setq arg (nth i args))

(princ (format "arg[%d] = %s\n" i arg))

(setq i (1+ i)))

(princ "\nrun shell command with shell-command-to-string\n")

(setq ret (shell-command-to-string "date"))

(princ (format "shell execute result = %s" ret))

(princ "\nstart speed test\n")

(setq num 0)

(setq total 0)

(setq start (current-time))

(while (<= num 10000000)

(setq total (+ total num))

(setq num (+ num 1))

)

(setq end (current-time))

(princ (shell-command-to-string "date"))

(setq cost (- (nth 1 end) (nth 1 start)))

(princ (format "loop for %d times cost %d s\n" num cost))

(princ (format "speed = %d loops/s\n" (/ num cost)))


运行结果:

xxx@ubuntu:~/src/emacs$ ./hello.el 1 2 3 "4 5 6 7 8"

This is message to stdout

This is err message to stderr

read command line with variable : (/usr/local/bin/emacs -scriptload ./hello.el 1 2 3 4 5 6 7 8)

enum arguments with car

arg[0] = /usr/local/bin/emacs

arg[1] = -scriptload

arg[2] = ./hello.el

arg[3] = 1

arg[4] = 2

arg[5] = 3

arg[6] = 4 5 6 7 8

enum arguments with nth

arg[0] = /usr/local/bin/emacs

arg[1] = -scriptload

arg[2] = ./hello.el

arg[3] = 1

arg[4] = 2

arg[5] = 3

arg[6] = 4 5 6 7 8

run shell command with shell-command-to-string

shell execute result = Mon Aug 17 21:09:36 HKT 2015

start speed test

Mon Aug 17 21:09:38 HKT 2015

loop for 10000001 times cost 2 s

speed = 5000000 loops/s

你可能感兴趣的:(『神器点滴之Emacs』用emacs编写shell script?)